Wednesday, 15 January 2020

JavaScript : Hoisting


In Java script, variables and functions are hoisted, what it means, we will try to understand it by examples:

if we are using variables without declaration like:


console.log(a); //ex 1 ; error : a is not defined

We will get error " ReferenceError : a is not defined.." so we will modify code to resolve error like :


var name;        // ex 2
console.log(name);

Now, we will get output "undefined" i.e. you have declared a variable but not defined it. In sort,    java script engine tells you,  there is a variable named 'name' and it's value is undefined. ['undefined' is a data type in java script.] what if we will write code like:

console.log(k);
var k="hello";

what would be the output of above code, will it throw error? or k = 'undefined' or k='hello',          based on ex1 we may say, code will throw error. but it's not correct, because of Hoisting.

Java script moves all the variable's and function's declaration on the top of scope before execution.
so above code will be like that:

var k;
console.log(k);
k="hello";
as a result of hoisting, program will print 'undefined' as we saw in ex2;

Hoisting is also applicable for function definitions. for example :
we can use function before it's definition like :

func1();
function func1(){
    console.log("from func1");
}

but it's not application in-case of function expression ( because their we are declaring a variable of type Function) below code will throw an error

func2(); //Error: func2 is not a function
var func2=function(){
    console.log("from func2");
};

to run above code we need function expression declaration before it's use
var func3=function(){
    console.log("from func3");
};
func3(); 

NOTE :
console.log(b); // veriable declare with 'let' are not hoisted.
let b=10;

No comments:

Post a Comment

JQuery : Quick Review

JQuery Selectors :selectors allows us to find a html elements so, we can manipulate it's attributes programmatically.  Id Sele...