Yep, you surely did… But what the heck is hoisting and how to handle it? Let’s see…
HOISTING PRELUDE ?
First time when it runs through the code, it makes safety checks (syntax checking etc) and small optimizations.
This compile run is also the time when hoisting occurs.
The second time when interpreter runs it executes our code line by line.
HOISTING, WHAT IS ALL ABOUT?
Hoisting is moving function declarations to the top of the current scope / function.
Let’s see two examples with different results:
var foo = "hello"; var bar = "world" ; console.log( foo + " " + bar); // "hello world"
var foo = "hello"; console.log( foo + " " + bar); // "hello undefined" var bar = "world";
In Example 2 as we can see, bar variable is declared because of the hoisting but no initial value is available to this variable.
That’s becuase initializations are not hoisted.
How interpreter sees it is like this:
var foo = "hello"; var bar; console.log( foo + " " + bar); // "hello undefined" bar = "world";
In order to avoid these kinds of bugs you might use ‘use strict’, which prevents variable to be used unless they are declared.
Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Did you stumble upon a…