Simplifying function hoisting in JavaScript

To understand function hoisting, let us start by considering the code listed below:

image

In any other programming language, the output here would be a reference error. However, in JavaScript you will get undefined as the output. Why? Because JavaScript hoists variables at the top of the execution context. An execution context could be the function in which a variable is declared, or a JavaScript file in which a variable is declared. So, let us rewrite the above code snippet using a function:

image

Here, the variable “foo” is hoisted at the top of function abc execution context; which means you can access foo before it is declared. To put it simply, whenever you declare a variable, the JavaScript interpreter breaks it into two statements:

  1. Declaration of variable
  2. Assignment

The declaration of a variable goes at the top of the execution context, and assignment happens where the variable is created. So the above code snippet is broken into two statements as shown in the image below:

The variable foo is hoisted at the top of the execution context of function abc, hence when you use it before its declaration, you get “undefined” as the output.

Keep in mind that a variable declared using the let statement does not get hoisted to the top of the execution context.

Now that you understand how variables are hoisted in JavaScript, let’s explore function hoisting in JavaScript. In JavaScript a function can be created in two ways:

Read full article on the Infragistics blog

Hoisting in JavaScript: Simplified

I often see JavaScript developers are struggling to understand HOISTING in JavaScript. In this post let us try to understand the hoisting in simple words.

All JavaScript variables are hoist at the top of the scope (function) in which they are defined. To understand it consider the code snippet shows below,

    var foo = "foo";
    console.log(foo);

Above code will print foo in the console. Simple isn’t it? Now let us go ahead and add a function as shown in below listing,

    var foo = "foo";
    console.log(foo);
    (function () {
        console.log(foo);
    }
    )();

foo will be printed twice on the console. We saw that a variable defined outside a function scope or in global function scope can be used inside other functions. Let us go ahead and modify the function as shown below,

 

    var foo = "foo";
    console.log(foo); // print foo

    (function () {

        console.log(foo); // print undefined
        var foo = "zoo";
    }
    )();

To be surprised now second console statement will print the value undefined. Well, why it is happening? These are the following reasons of that,

  • We have again declared foo inside the anonymous function.
  • As we discussed earlier, JavaScript always hoist a variable declaration at the top of the scope. It only hoist the declaration not the initialization.

In actual, above anonymous function can be seen as below. Declaration has been moved to the top of the function scope, whereas initialization is done at the place variable is declared.

clip_image002

In above function, we are trying to access variable foo before it is initialized and that’s the reason we are getting undefined value printed. There are two types of scoping in the JavaScript,

  • Function scope
  • Global scope

Always a variable is hoisted at either the top of the function scope or global scope. When you use var to declare a variable inside a function, then that variable is inside that particular function scope. When you declare a variable without using var, it is always in the global scope. I hope now you have better understanding of hoisting in JavaScript

You can also read an explanation on LET which is part of ES6 Derick Bailey blog

Variable Scoping and Hoisting in JavaScript

Variable Scoping in JavaScript is quite different than other programming languages like C. In this post we will learn variable scoping in JavaScript.

Simply putting, Scope of a JavaScript variable is within region of the program it is defined. So a variable defined inside function will have scope inside that function.

Consider following code snippet,

var globalvar = "Global Variable";

 function funct1() {

var gloabalvar = "Local Variable";
 console.log(gloabalvar);
 return globalvar;
 }
 console.log(globalvar);
 var result = funct1();
 console.log(result);

You will get output as following,

clip_image001

You can see that scope of variable is within the region it is defined. We are getting second output as Local Variable because scope of globalvar is overridden in funct1 function.

Essentially variable globalvar has two different scope in above code. It has been changed inside funct1 function. So when you print its value inside funct1, you get ouput as Local Variable and outside that its value is Global Variable.

Now consider second example in this. In below example we are defining variable without keyword var.


globalvar = "Global Variable";

 function funct1() {

gloabalvar = "Local Variable";
 console.log(gloabalvar);
 return globalvar;
 }

 funct1();
 console.log(gloabalvar);

In above example inside function globalvar is getting modified and it is modifying globally scope variable. When you define a variable without var keyword, its scope is global. Output of above code would be as follows,

clip_image001[6]

Function Scope

In JavaScript works on Function Scope. In Function Scope variables are visible inside function they are defined and inside any nested function of that function.

Consider following example,


function funct1() {
 var i = 10;
 if (i == 10) {

var j = 9;
 for (var m = 0 ; m < 9 ; m++) {
 console.log(m);
 }

&nbsp;

}

console.log(m);
 console.log(j);
 console.log(i);

 }

 funct1();

In above code we are variable j and m inside if and for block respectively. In language like C there scope is limited to block they are defined. However JavaScript works on Function Scope so variable j and m are visible throughout the function. We are printing them outside block in which they are defined and JavaScript is printing them. Output of above code would be as follows,

image

JavaScript Hoisting

Just we learnt that JavaScript variables are scoped throughput the function in which they are defined. In JavaScript variables are visible before they are declared and this is known as Hoisting in JavaScript. JavaScript assumed that all the variables are declared at the top of the function. In other words all the variables are hoisted at the top of the functions.

Consider following example,


var i = 9;
 function funct1() {
 console.log(i);
 var i = 99;
 console.log(i);
 }

 funct1();
 console.log(i);

As output you will find that second print statement will print undefined. Reason behind this even if I is initialize in second line of function, it is visible throughput the function. Since I is hoisted in function so you get undefined for second print. Output of above code snippet is as follows,

clip_image001[8]

In Block Scope programming language it is better to define variables as near as possible to where they are used. Whereas due to hoisting and Function Scope in JavaScript it is better to declare a variable at the top of function.

A good understanding of Function Scope, Hoisting in JavaScript is important to write better codes. I hope you find this post useful. Thanks for reading.