Thursday, September 29, 2016

Why is it Important to Understand JavaScript Hoisting

Before moving on with the post, just consider the following very simple JavaScript code.
x = 5;
var x;
console.log(x);
If you think the above code will give an error, then I am sorry, you might not know what JavaScript Hoisting is. Above will print "5" to the console without any errors. The reason is Hoisting in JavaScript.

Basically JavaScript Hoisting is moving declarations to the top while the JavaScript Interpretation. Even though you have written you code like above, following is what actually gets executed.
var x;
x = 5;
console.log(x);
Notice that declaration of x is being moved to the top.

Now let's take a look at what's Hoisting’s effect on functions. Consider the following code. Here I have two functions, one is a function declaration and the other is a function expression.
foo();
bar();
 
function foo() {
    console.log("foo");
};
 
var bar = function() {
    console.log("bar");
};
Here if you run this, "foo" will be printed on the console, and then when the call to bar() is getting executed, it will throw TypeError: bar is not a function. What’s happening here is again Hoisting. What is getting executed is the following code.
var bar;
 
function foo() {
    console.log("foo");
};
 
foo();
bar();
 
bar = function() {
    console.log("bar");
};
Here is also the declarations has moved to the top.

Now I hope you figured why it is so important to understand this little but very critical concept.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment