in JavaScript by
Q:
Explain Hoisting in javascript.

1 Answer

0 votes
by

Hoisting is a default behaviour of javascript where all the variable and function declarations are moved on top.

This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.

Example 1:

hoistedVariable = 3;

console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized

var hoistedVariable;

Example 2:

hoistedFunction();  // Outputs " Hello world! " even when the function is declared after calling

function hoistedFunction(){ 

  console.log(" Hello world! ");

}

Example 3:

// Hoisting takes place in the local scope as well

function doSomething(){

  x = 33;

  console.log(x);

  var x;

}

doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope

**Note - Variable initializations are not hoisted, only variable declarations are hoisted:

var x;

console.log(x); // Outputs "undefined" since the initialization of "x" is not hoisted

x = 23;

**Note - To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:

"use strict";

x = 23; // Gives an error since 'x' is not declared

var x; 

Click here to read more about JavaScript
Click here to read more about Insurance

Related questions

0 votes
asked Dec 10, 2020 in JavaScript by SakshiSharma
0 votes
asked Dec 10, 2020 in JavaScript by SakshiSharma
0 votes
asked Aug 24, 2020 in JavaScript by Hodge
0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
0 votes
asked Feb 6, 2020 in JavaScript by rajeshsharma
...