Hoisting With Functions

Introduction

In JavaScript, there are two different ways of defining a function. The first is function declaration and the second is function expressions.

Function declaration is the syntax of the function keyword, the name of the function then paratheses. Example below:

function isEven(num) {  
  return num % 2 === 0;
} 

Function expressions is the syntax of the variable keyword, the name of the function equals paratheses. Example below:

let isEven = function(num) {  
  return num % 2 === 0;
} 

The question most programmers have after learning both of these syntaxes is which is better? The answer is Function expressions. To understand why we must learn about something called hoisting.


Explained

Hoisting is JavaScript's Interpreter moving all declarations to the top of the context before running any code. What does that mean? See the example below:

console.log("Code before");

function hello(name) {  
  console.log("Hello " + name);
}

let x = 2;  
hello("Billy");  
x = 10;  

What JavaScript's Interpreter changes the code to be:

function hello(name) {  
  console.log("Hello " + name);
}
let x;

console.log("Code before");  
x = 2;  
hello("Billy");  
x = 10;  

You will notice that it took the declaration of the function and the variable to the top of the code. It did not hoist the assignment of the variable.

Why does that matter? Check out the code below. What do you think the output of the code should be?

console.log(addNums(1, 3));

function addNums(a, b) {  
  return a + b;
}

If you were to run this code you would see the number 4 in your console. That is because JavaScript's Interpreter changes your code before running to this:

function addNums(a, b) {  
  return a + b;
}
console.log(addNums(1, 3));  

That's good because we wrote code and it works but bad because hoisting has allowed writing code out of logical order. Your code should always read top to bottom.


Fix

Taking advantage of function expressions we can force ourselves to write code in logical order. Check out the example below.

console.log(divNums(1, 3));

let divNums = function(a, b) {  
  return a / b;
}

Will be read as:

let divNums;  
console.log(divNums(1, 3));

divNums = function(a, b) {  
  return a / b;
}

This code will throw an error because divNums will not have been assigned to a function. This is because hoisting only hoists declaration of the function and the variable to the top of the code. It will not hoist the assignment of the variable.

Code written correctly:

let divNums = function(a, b) {  
  return a / b;
}
console.log(divNums(1, 3));  

Summary

When writing functions we should use function expressions because they are not hoisted. This forces us to write our code in logical order. This makes it easier to debug and read.