Functions

A function is a named block of code that performs a specific task as described by its name. They can take inputs (called arguments) and return a value. Sometimes they won't return a value though and that's okay. If a function doesn't return a value, we say that it "returns void" or "is void".

The value returned by a function can be assigned to a variable, and used by other bits of code.

console.log is a function. It writes some data to the console, but doesn't return a value for us to use, so it returns void

You can make your own functions too, like this:

function doubleNumber(number) {
    var doubled = number * 2;
    return doubled;
}

var myNumber = doubleNumber(4);

alert(myNumber);

In the above example, we have created a function called doubleNumber. The name is arbitrary, we could have named it whatever we want, but generally speaking it is a good idea to name the functions something sensible which clearly describes what the code inside will be doing. In this case it will be returning 2 times the value provided as an argument, so doubleNumber is a simple, appropriate name.

Our function also takes an argument. The argument name is also arbitrary, and we could have named it whatever we want as well. In this case, I have called it number for simplicity. The most important thing when naming variables and functions is that their purpose and usage can be accurately guessed by someone else reading the code, just by looking at the name.

When we define a function, the function gets assigned to a variable with the same name as the function. There is an important distinction to make here. Using the above function as an example, if we use console.log to examine it, look at what happens.

console.log(doubleNumber)
ƒ doubleNumber(number) {
    var doubled = number * 2;
    return doubled;
}

Because we have passed in the variable containing the function, console.log is showing us the definition of the function. It shows us what the variable contains, but it does not execute or "call" the function.

If we want to call the function, we need to suffix it with parenthesis and pass in a value for any arguments we have defined for the function. In this case, we have specified that doubleNumber takes a single argument, so in order to call it and get a value back we can do something like this:

const newNumber = doubleNumber(4);
console.log(newNumber); // this will output 8

Summary:

  • Defining a function creates a variable containing our code

  • To call the function, we need to use the variable name suffixed with a pair of parenthesis ()

    • We can pass any arguments we have specified between these parenthesis

    • Make sure you don't have any spaces or unexpected characters between the function name and the parenthesis

Last updated