CommonLounge Archive

JavaScript: Functions

September 26, 2018

In the tutorials so far in this course, you’ve used functions many times. In this tutorial, you’ll see how to create new ones! You’ll also learn about some more built in functions.

Your own functions!

Remember functions like prompt() that you can execute in JavaScript? Well, good news – you will learn how to write your own functions now!

A function is a sequence of instructions that JavaScript should execute. Each function in JavaScript generally starts with the keyword function, has a name, and has some parameters. Let’s give it a go. Create a file called "functions.html" with the following code in it:

<html>
  <head>
    <script>
      function hello() {
          document.write("Hi there!", "<br>");
          document.write("How are you?", "<br>");
      }
      hello();
    </script>
  </head>
</html>

Okay, our first function is ready!

You may wonder why we’ve written the name of the function in the last line of our JavaScript code. The first time (line 4), we’re giving the function a name and defining what it does. The second time (line 8), we’re calling the function, i.e. asking JavaScript to actually execute the function.

If you run this, you should see:

Hi there!
How are you?

as expected.


Let’s build our first function with parameters. We will use the previous example – a function that says ‘hello’ to the person running it – with a name:

function hello(name)

As you can see, we now gave our function a parameter that we called name:

<html>
  <head>
    <script>
      function hello(name) {
          if (name === "Commonlounge")
              document.write("Hello Commonlounge!", "<br>");
          else if (name === "Dave")
              document.write("Hello Dave!", "<br>");
          else
              document.write("Hello anonymous!", "<br>");
      }
      hello();
    </script>
  </head>
</html>

Within the function, a parameter works exactly the same as a variable.

Let’s see how it works now:

Hello anonymous!

Because we didn’t pass any argument(name) to the function, the value that name gets is undefined. Therefore, it goes to the else block and "Hello anonymous!" gets printed.

We’re using the words parameters and arguments interchangeably. We think parameters is much more clear to a beginner, but arguments is the word used conventionally.

Let’s fix the function call:

hello("Commonlounge");

and run it again; you should see "Hello Commonlounge!" printed on the page.

This is awesome, right? This way you don’t have to repeat yourself every time you want to change the name of the person the function is supposed to greet. And that’s exactly why we need functions – you never want to repeat your code!

Try calling the function with different arguments and see what the output is.


Let’s do something smarter – if there are more names than two, writing a condition for each would be hard, right?

<html>
  <head>
    <script>
      function hello(name) {
        document.write("Hello " + name + "!", "<br>");
      }
      hello("Rachel");
    </script>
  </head>
</html>

You should see "Hello Rachel!", when you run this code.


There are other alternative syntax for defining functions:

<html>
  <head>
    <script>
      var hello = function(name) {
        document.write("Hello " + name + "!", "<br>");
      }
      hello("Rachel");
    </script>
  </head>
</html>

There’s a short-hand for this as well:

<html>
  <head>
    <script>
      var hello = (name) => {
        document.write("Hello " + name + "!", "<br>");
      }
      hello("Rachel");
    </script>
  </head>
</html>

These functions are called arrow functions.

The syntax you saw up-first is the most popular. But it’s good to know other ways of writing functions, specially if you are ever reading code written by someone else and they prefer using the alternative syntaxes.

Multiple parameters and return values

So far, you have seen functions which take one parameter, and print something based on that. In fact, a function can take multiple inputs, and also return a value. Here’s a simple example,

function subtract(x, y) {
    return x - y;
}
var z = subtract(5, 2);
console.log(z);

The above subtract function takes two inputs, which it calls x and y. It then returns the result of subtracting y from x. Hence, when we call subtract(5, 2), the returned value is 3. You can assign this value to a variable, or use it any other way you want.

Also, recall that you have already used functions before which return a value (e.g., prompt). Now you can write your own!

When evaluating an expression, functions evaluate to the value they return. For example:

subtract(5, 2) + 8;
=> 3 + 8
=> 11 

Note that you can also return a string, array, object, etc. Here’s an example of a function which returns an object:

<html>
  <head>
    <script>
      function math(x, y) {
          return {
              "sum": x + y, 
              "difference": x - y,
              "product": x * y,
              "quotient": x / y
          };
      }
      console.log(JSON.stringify(math(5, 4)));
    </script>
  </head>
</html>

You should see the answer in the console

You can also print the object on the page using document.write but, the way to do that is not so direct. If you simply write

document.write(math(5, 4));

You will see

[object Object]

which is not what you expected, right? Let’s not worry about it for now and move on. We’ll learn how to print values of an object later in this course.

Sorting

In the tutorial about arrays, we learnt that to sort an array with numerical values we have to provide a comparison function which compares the two numbers and returns a negative, zero, or positive value.

  • A negative value implies that the first number is less than the second
  • 0 value implies that the numbers are the same
  • A positive value implies that the second number is greater than the first

Now that we know about functions and return values, let’s learn how to sort an integer array:

var numarray = [3, 5, 12, 1, 512];
function compare(a, b) {
    return a - b;
}
numarray.sort(compare);
console.log(numarray);

This prints numarray sorted in increasing order. You can rewrite this and shorten the code by using an arrow function.

var numarray = [3, 5, 12, 1, 512];
numarray.sort((a, b) => { return a - b; });
console.log(numarray);

That’s pretty cool, right?

undefined type

Remember when we used to run some commands on the console and the console used to print undefined along with the output?

If you don’t return anything from a function, by default it returns undefined. The global undefined property represents the primitive value undefined. It is one of JavaScript’s primitive types.

  • A variable that has not been assigned a value is of type undefined.
  • A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.
  • A function returns undefined if a value was not returned.

Optional arguments

There’s one last thing about functions you should know - optional arguments.

Take a look at the function below:

function hi(name="Commonlounge") {
  console.log("Hi " + name + "!");
}
hi();                // "Hi Commonlounge!"
hi("Alice");         // "Hi Alice!"

In the above, function hi(name="Commonlounge") means that if the argument name is not given when calling the function (line 4), the default value of name will be "Commonlounge".


Let’s see an example with multiple parameters with default values, with all the ways you can call it:

function greet(name="Commonlounge", greeting="Hi") {
  console.log(greeting + " " + name + "!");
}
greet()                                // Hi Commonlounge!
greet("Alice")                         // Hi Alice!
greet("Alice", "Hello")                // Hello Alice!

Finally, you can also write functions where some arguments have default values and others don’t. For example:

function greet(name, greeting="Hi") {
  console.log(greeting + " " + name + "!");
}

In the above function, name has no default value, and greeting does. So you can call it in the following ways:

function greet(name, greeting="Hi") {
  console.log(greeting + " " + name + "!");
}
greet("Alice")                         // Hi Alice!
greet("Alice", "Hello")                // Hello Alice!

In all cases, the first argument must be passed. Only the second argument is optional.

Note: If you define a function where a parameter with default value is listed before a parameter with no default value, you’ll never be able to use the default value. For example, suppose you define function greet(greeting="Hi", name). Now, you need to pass name, since it doesn’t have any default value. But the first parameter is greeting, and there is no way to provide the second parameter (name) without providing the first parameter. For example, greet("Alice") just passes "Alice" as parameter greeting, and name is undefined. Hence, there’s no way to call the function greet where the default value for greeting will actually get used.


Congratulations! You just learned how to write functions! :)

Conclusion

That’s it. You totally rock! This was a tricky chapter, so you should feel proud of yourself. We’re definitely proud of you for making it this far!


© 2016-2022. All rights reserved.