Hoisting in JavaScript Explained

January 06, 2018


Hoisting is a process in which all variables and method declarations are moved to the top of the executing program, no matter at what position we write them.
In other words, a variable or a function can be used even before its declaration in a code block.
doSomething();

function doSomething()
{
   val = 10;
   val += 11;

   console.log(val);

   var val;
}
Output
21

Here, we are assigning (val=10), altering (val += 11) and logging (console.log) the value of the variable val even before the declaration of the variable. Also, we are calling the method before its declaration and still the code is working. This mechanism is called Hoisting.
Now, consider this hoisting mechanism:
function doSomethingNew()
{
   console.log(val);
   var val = 10;
}

doSomethingNew();
Output
undefined
Calling the doSomethingNew() method gives undefined. But why?
This is because the interpreter follows a defined flow which involves:
Javascript interpreter flow

In doSomethingNew() method, the variable val is declared first.
In javascript, all variables are initialized with the default value undefined.
Then we log the variable on Line 3 which will give undefined. Finally, the value 10 would get assigned to the variable val.
So the actual code created by the interpreter would look like:
function doSomethingNew()
{
   var val;
   console.log(val);

   val = 10;
}

doSomethingNew();
Now, using the val after assigning it value will give its value as 10 like the code below.
function doSomethingAgain()
{
   console.log(val);
   var val = 10;
   console.log(val);
}

doSomethingAgain();
Output
undefined
10

Scope for Hoisting

The scope for hoisting is limited to the code block in which the code is executing. This means we are able to access the variables only in the code block where the variable is accessible.
var a;

function demo()
{
   a = 10;
   var b = 20;

   console.log("Inside demo function");
   console.log(a);
   console.log(b);
}

demo();

console.log("Outside demo function");
console.log(a);
console.log(b);
Output
Inside demo function
10
20
Outside demo function
10
Uncaught ReferenceError: b is not defined
As you can see, we get a reference error when we try to access the variable b outside demo function. This is because the scope of variable b is limited to demo method and we cannot use it outside.

Strict Mode

ES5 has a strict mode that prevents hoisting. All we need to do is to write 'use strict'; statement before the javascript code and the browser will give an error stating that the variable is not defined in case of hoisting.

You Might Also Like

0 comments