JavaScript Hoisting

JavaScript Hoisting

JavaScript hoisting is a mechanism where variable and function declarations to their contained scope during the compilation. JavaScript is an important concept to understand how variables and functions are manipulated during code execution. This guide will solve into the features, and implications of hoisting in JavaScript, covering basic topics such as the variable declaration, function scope, and the differences between var, let, and const declarations.

JavaScript hoisting is a mechanism where variable and function declarations to their contained scope during the compilation. JavaScript is an important concept to understand how variables and functions are manipulated during code execution. This guide will solve into the features, and implications of hoisting in JavaScript, covering basic topics such as the variable declaration, function scope, and the differences between var, let, and const declarations.

What is Hoisting in JavaScript?

What is Hoisting in JavaScript?

Hoisting is an important topic in JavaScript where declarations of variables and functions are moved to the top of their scopes during the compilation time. This ensures that in any case where variables and functions are defined within a scope, they are accessible all over that scope.

Hoisting is an important topic in JavaScript where declarations of variables and functions are moved to the top of their scopes during the compilation time. This ensures that in any case where variables and functions are defined within a scope, they are accessible all over that scope.

Features of Hoisting

Features of Hoisting

  • Declarations are hoisted, not initializations.
  • Allows calling functions before their declarations.
  • All variables and function declarations are processed before any code execution.
  • When assigned a value undeclared variables are created as global variables.

Note: JavaScript only hoists declarations, not initializations.

JavaScript allocates memory for all variables and functions defined in the program before execution.

  • Declarations are hoisted, not initializations.
  • Allows calling functions before their declarations.
  • All variables and function declarations are processed before any code execution.
  • When assigned a value undeclared variables are created as global variables.

Note: JavaScript only hoists declarations, not initializations.

JavaScript allocates memory for all variables and functions defined in the program before execution.

Sequence of variable declaration

Sequence of variable declaration

The following is the sequence in which variable declaration and initialization occur. 

Declaration –> Initialisation/Assignment –> Usage 

The following is the sequence in which variable declaration and initialization occur. 

Declaration –> Initialisation/Assignment –> Usage 

Variable lifecycle

Variable lifecycle

let abc;                  // Declaration
abc = 100;            // Assignment
console.log(abc);  // Usage

However, since JavaScript allows us to both declare and initialize our variables simultaneously, so we can declare and initialize at the same time.  

let abc = 100;

Note: Always remember that external JavaScript declares variables first and then initializes them. It is also good to know that variable declarations are processed before any code is executed.

However, in JavaScript, undeclared variables do not exist until the code that assigns them is executed. Thus, assigning a value to an undeclared variable in case creates it as a global variable when the code is executed. This means that all undeclared variables are global variables.

let abc;                  // Declaration
abc = 100;            // Assignment
console.log(abc);  // Usage

However, since JavaScript allows us to both declare and initialize our variables simultaneously, so we can declare and initialize at the same time.  

let abc = 100;

Note: Always remember that external JavaScript declares variables first and then initializes them. It is also good to know that variable declarations are processed before any code is executed.

However, in JavaScript, undeclared variables do not exist until the code that assigns them is executed. Thus, assigning a value to an undeclared variable in case creates it as a global variable when the code is executed. This means that all undeclared variables are global variables.

Examples of JavaScript Hoisting

Examples of JavaScript Hoisting

  1. Global Scope

Javascript

// Hoisting

function hoist() {

    a = 10;

    let b = 50;

}

hoist();

console.log(a); // 10

console.log(b); // ReferenceError : b is not defined

Output:

10
ReferenceError: b is not defined

Explanation: In the above example, hoisting allows access to variables declared as var before declaration, but not those declared as let or const. So, a is accessible, but b throws a ReferenceError

Note: There’s a difference between ReferenceError and undefined errors. An undefined error occurs when we have a variable that is undefined or explicitly defined as type undefined type. A ReferenceError is thrown whilst trying to access a previously undeclared variable. 

  1. JavaScript var hoisting

When we talk about ES5, the variable that comes into our thought is var. Hoisting with var is somewhat different. When it is compared to let/const. Let’s see how hoisting works.

Example:

Javascript

// var code (global)

console.log(name); // undefined

let name = ‘Rakul’;

Output: 

ReferenceError: Cannot access ‘name’ before initialization

Explanation: Explanation: In the above code example variables declared by var are hoisted but not initialized, resulting in undefined when access point before declaration. Variables declared with let or const do not exhibit this behavior.
But the interpreter sees this differently, let’s see the above code like this:

Javascript

// how interpreter sees the above code

let a;

console.log(a); // undefined

a = ‘Sudip’;

Output

undefined

  1. Function scoped variable

Let’s look at how function-scoped variables are hoisted.

Example:

Javascript

// Function scoped

function xy() {

  console.log(name);

  let name = Ram’;

}

xy(); // Undefined

Output: 

undefined

There is no difference compared to the code when we declared the variable globally.
Example: We get undefined as code that the interpreter sees.

Javascript

function xy() {

  let name;

  console.log(name);

  name = ‘Ram’;

}

xy(); // undefined

Output

undefined

To avoid this pitfall, we can ensure that the variable is declared and assigned simultaneously before it is used.

Example:

Javascript

function xy() {

  let name = ‘Ram’;

  console.log(name); // Ram

}

xy();

Output

Ram

  1. JavaScript hoisting with Let

We know that variables declared with let keywords are block scoped and not function scoped so there is no problem with hoisting. 

Example:  

Javascript

//let example(global)

console.log(name);

let name = ‘Sham’; // ReferenceError: name is not defined

Output: 

ReferenceError: name is not defined

Explanation: Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first. 

  1. JavaScript hoisting with const

It behaves similarly to let when it comes to hoisting. A function as a whole can also be hoisted and we can call it before the declaration.

Example:

Javascript

fun(); // Calling before declaration

function fun() { // Declaring

  console.log(“Function is hoisted”);

}

Output

Function is hoisted

Also, if a function is used as an expression and we try to access it before the assignment an error will occur as only declarations are hoisted.

Example:

Javascript

fun() // Calling the expression

let fun = () =>{ // Declaring

    let name = ‘Risu’;

    console.log(name);

}

Output: 

ReferenceError: Cannot access ‘fun’ before initialization

However, if var is used in the expression instead of let we will get the following Type Error as follows.

  1. Hoisting with Functions

Example:

Javascript

func() // Calling the expression

var func = () =>{ // Declaring

    let name = ‘Siya’;

    console.log(name);

}

Output:

TypeError: fun is not a function

  1. Global Scope

Javascript

// Hoisting

function hoist() {

    a = 10;

    let b = 50;

}

hoist();

console.log(a); // 10

console.log(b); // ReferenceError : b is not defined

Output:

10
ReferenceError: b is not defined

Explanation: In the above example, hoisting allows access to variables declared as var before declaration, but not those declared as let or const. So, a is accessible, but b throws a ReferenceError

Note: There’s a difference between ReferenceError and undefined errors. An undefined error occurs when we have a variable that is undefined or explicitly defined as type undefined type. A ReferenceError is thrown whilst trying to access a previously undeclared variable. 

  1. JavaScript var hoisting

When we talk about ES5, the variable that comes into our thought is var. Hoisting with var is somewhat different. When it is compared to let/const. Let’s see how hoisting works.

Example:

Javascript

// var code (global)

console.log(name); // undefined

let name = ‘Rakul’;

Output: 

ReferenceError: Cannot access ‘name’ before initialization

Explanation: Explanation: In the above code example variables declared by var are hoisted but not initialized, resulting in undefined when access point before declaration. Variables declared with let or const do not exhibit this behavior.
But the interpreter sees this differently, let’s see the above code like this:

Javascript

// how interpreter sees the above code

let a;

console.log(a); // undefined

a = ‘Sudip’;

Output

undefined

  1. Function scoped variable

Let’s look at how function-scoped variables are hoisted.

Example:

Javascript

// Function scoped

function xy() {

  console.log(name);

  let name = Ram’;

}

xy(); // Undefined

Output: 

undefined

There is no difference compared to the code when we declared the variable globally.
Example: We get undefined as code that the interpreter sees.

Javascript

function xy() {

  let name;

  console.log(name);

  name = ‘Ram’;

}

xy(); // undefined

Output

undefined

To avoid this pitfall, we can ensure that the variable is declared and assigned simultaneously before it is used.

Example:

Javascript

function xy() {

  let name = ‘Ram’;

  console.log(name); // Ram

}

xy();

Output

Ram

  1. JavaScript hoisting with Let

We know that variables declared with let keywords are block scoped and not function scoped so there is no problem with hoisting. 

Example:  

Javascript

//let example(global)

console.log(name);

let name = ‘Sham’; // ReferenceError: name is not defined

Output: 

ReferenceError: name is not defined

Explanation: Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first. 

  1. JavaScript hoisting with const

It behaves similarly to let when it comes to hoisting. A function as a whole can also be hoisted and we can call it before the declaration.

Example:

Javascript

fun(); // Calling before declaration

function fun() { // Declaring

  console.log(“Function is hoisted”);

}

Output

Function is hoisted

Also, if a function is used as an expression and we try to access it before the assignment an error will occur as only declarations are hoisted.

Example:

Javascript

fun() // Calling the expression

let fun = () =>{ // Declaring

    let name = ‘Risu’;

    console.log(name);

}

Output: 

ReferenceError: Cannot access ‘fun’ before initialization

However, if var is used in the expression instead of let we will get the following Type Error as follows.

  1. Hoisting with Functions

Example:

Javascript

func() // Calling the expression

var func = () =>{ // Declaring

    let name = ‘Siya’;

    console.log(name);

}

Output:

TypeError: fun is not a function

End

Leave a Reply

Your email address will not be published. Required fields are marked *