Table of Contents

How to Create Functions in JavaScript

Code Playground is only enabled on larger screen sizes.

In this lesson, we'll discuss more about functions.

There are three different ways to define a function: function expression, function declaration, and arrow function.

Function expression

Let's start with the function expression syntax.

For instance, here is an example of a function that counts all even numbers in the array:

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

The keyword function defines a function:

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

The parentheses define the input arguments for the function:

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

In this example, the function only accepts one input argument, arr, which can then be used inside the function as a variable.

Look inside the function body, defined by the curly braces ({}), and notice that the input argument arr is treated as an array, and we are iterating over the array with the for of loop.

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

At the end of the function body, right before the closing }, the final result (n) will be returned using the keyword return:

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

The function will terminate after the return statement, so any statements afterward will be ignored.

If you don't have a return statement in the function, that function will return undefined.

Lastly, the function will be assigned to countEven, just like a variable:

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

To invoke that function, call by its name and pass the required input arguments.

javascript
let countEven = function (arr) {
  let n = 0;
  let e;
 
  for (e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};
 
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(countEven(arr)); // -> 5

The built-in function console.log(), which we've seen many times in this course, will take the output of countEven(), and print it to the console.

This syntax is called function expression. Some people find it difficult to write, compared to the function declaration syntax which we are going to discuss later, but it does demonstrate the true nature of a function.

A function is just a piece of code as a value, which is then assigned to a variable.

Function declaration

There is also a slightly shorter way of creating a function called function declaration, which is demonstrated below:

javascript
function countEven(arr) {
  let n = 0;
 
  for (let e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
}

Here we are using the same function keyword, countEven is the function name, and everything else remains the same.

This function can be called in the exact same way:

javascript
let arr = [1, 2, 3];
 
countEven(arr);

Arrow function

Alternatively, there is a special syntax called arrow function in JavaScript, which aims to provide an even shorter way to create functions.

javascript
let countEven = (arr) => {
  let n = 0;
 
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      n++;
    }
  }
 
  return n;
};
 
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(countEven(a));

The name arrow function comes from the arrow (=>).

javascript
let countEven = (arr) => {
  let n = 0;
 
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

The arrow function can be expressed in a compact format under certain scenarios.

For example, the parentheses can be omitted when the function only takes one input parameter.

javascript
// prettier-ignore
let countEven = arr => {
  // . . .
};

When the function body has only a return statement, the curly braces and even the keyword return can be omitted.

javascript
// prettier-ignore
let calcSquare = x => x * x;
 
console.log(calcSquare(5)); // -> 25

The differences

These three methods do have some slight differences.

First of all, by default, JavaScript executes the code line by line.

When using the function expression syntax, you can only call a function after it has been declared.

javascript
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(countEven(arr)); // Function countEven is called here
 
// But declared here
let countEven = function (arr) {
  let n = 0;
 
  for (let e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};

In this example, the function countEven() is called before it is declared. And this code will return an error.

text
/Users/. . ./index.js:3
console.log(countEven(arr));
            ^
 
ReferenceError: Cannot access 'countEven' before initialization
    at Object.<anonymous> (/Users/. . ./index.js:3:13)
    . . .
 
Node.js v20.12.2

The arrow function works the same. An error will be returned if you try to call an arrow function before it is declared.

javascript
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(countEven(arr)); // Function countEven is called here
 
// But declared here
let countEven = (arr) => {
  let n = 0;
 
  for (let e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
};
text
/Users/. . ./index.js:3
console.log(countEven(arr));
            ^
 
ReferenceError: Cannot access 'countEven' before initialization
    at Object.<anonymous> (/Users/. . ./index.js:3:13)
    . . .
 
Node.js v20.12.2

However, the function declaration method is different.

JavaScript will compile all the declared functions first, and then start to execute the code from the very beginning, which means you can call a function before it is declared.

javascript
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
console.log(countEven(arr));
 
function countEven(arr) {
  let n = 0;
 
  for (let e of arr) {
    if (e % 2 === 0) {
      n++;
    }
  }
 
  return n;
}

This provides you with a more flexible way to organize your functions.

For example, you can place all of your functions together at the beginning or the end of the file, without worrying about any conflicts.

Another difference has to do with the this keyword, which refers to the current instance of the object. Arrow functions don't have a this keyword like regular functions.

We will come back to this topic later.