Hoisting in JavaScript

Have you ever wondered why you were able to call functions before you wrote them in your code? This is possible thanks to hoisting.

Hoisting is a process of moving the declaration of variables and functions to the top by the interpreter. This happens during compilation, before code execution.

So no matter where variables and functions are declared, they are moved to top of their scope. It allows functions to be used in code before they are declared in the code.

printName("John"); // Output: 'My name is John'

function printName(name) {
  console.log("My name is " + name);
}

variables are partially hoisted

It’s important to remember that functions are fully hoisted but variables are only partially hoisted. This is because JavaScript only hoists declarations, not initializations.

In other words, JS engine is allocating variables in memory but without their value. Their values get assigned (initialization) during code execution. Before execution, the variable has its default initialization: it’s undefined for variables declared using var, otherwise uninitialized.

console.log(name); // returns 'undefined' (JavaScript has hoisted the variable declaration only)

var name = 'John'; // initialization and declaration 

console.log(name); // after the line is executed, it returns 'John'

Because of this, we can use variables before we declare them. However, we have to be careful because the hoisted variable can be initialized with undefined.

let and const hoisting

With const and let, just as with var, the variable is hoisted to the top of the block, but it is not initialized with a default value. So an exception (Reference error) will be thrown if a variable declared with let or const is used before it is initialized.

console.log(name); // Output: ReferenceError: name is not defined
const name = 'John';

using ‘strict mode’

We can also use strict mode that was introduced in the es5 version of JavaScript. In a restricted mode, the compiler won’t tolerate the usage of variables before they are declared.

'use strict';

console.log(name); // Output: ReferenceError: name is not defined
name = 'John';

Function expressions vs declarations

Function declarations are hoisted completely to the top, but we should not forget that function expressions (similar to variables) are not fully hoisted. Function expressions are hoisted to the top of the block, but they are not initialized until code is executed.

declaration(); // This function has been hoisted

// Function declaration
function declaration() {
  console.log('I am hoisted');
};

expression(); // Output: "TypeError: expression is not a function

// Function expression
var expression = function() {
  console.log('I am declared during execution');
};

This website is owned by Mateusz Janusz who is a software developer. He writes here about things that he is interested in or is currently learning.
You can find him also at Github and contact on LinkedIn.