Running a Function

Functions execute when the function is called. This process is known as invocation. You can invoke a function by referencing the function name, followed by () .

Lets look at the example below. We have a function named logIt . This function requires one parameter, name . The function will then log that name back to the console.

function logIt(name){

console.log(name);

}

To invoke our function, we call it, while passing in the singular parameter. Here I am calling this function with the name Dave:

logIt('Dave');

A function with no parameters is simply invoked with an empty set of parenthesis:

function logIt2(){

console.log('Log it 2');

} logIt2();

Returning from a function

Every function in JavaScript returns undefined unless otherwise specified. We can test this by creating and invoking an empty function:

function test(){}; test();

// undefined

As expected, we get undefined returned.

We can use the return keyword to specify what we want a function to return. Look at the example below:

function test(){

return true;

}; test();

// true

In this example we tell the function to return true . when we invoke the function, we get true displayed in the console.

Another important rule of the return statement is that it stops a functions execution immediately.

Consider this example where we have two return statements in our test function:

function test(){

return true;

return false;

}; test();

// true

The first return statement immediately stops execution of our function and causes our function to return true . The code on line three: return false; is never executed.

Something else to understand about the return statement is that it’s value is returned to the caller of the function. Let’s look at an example:

let double = function(num) {

return num * 2;

}

Above we have a function expression. The variable double is being assigned to the returned value of this anonymous function. When we invoke the function we can see this assignment in action:

let test = double(3); console.log(test);

// 6

Awesome! The return variable not only returns values from a function, but it assigns them to whatever called the function!

Functions are Objects

In JavaScript, anything that is not a primitive type ( undefined , null , boolean , number , or string ) is an object. Objects in JavaScript are extremely versatile. Because of this, we can even pass a function as a parameter into another function.

When a function accepts another function as a parameter, or returns a function, it is called a higher-order function. You’ve probably already used a bunch of higher order functions and don’t even know it: Array.prototype.map and Array.prototype.filter are higher order functions (Just to name a couple). More on this topic in a future article…

What to remember

That’s a lot of information. Here’s what you should remember: