Variable hoisting explained
"What does variable hoisting mean?"
Variable declarations moved to top of function
Variable hoisting means that all
var statements in a function are moved to the top of the function regardless of their location in the function. For example
Note how the declaration of variable
b has changed place.
Declaration and initialization split into two
This moving of
var statements only applies to the declaration of a variable. If there's an initialization combined with the declaration, the initialization stays where it is. This means that putting a variable declaration statement with an initializer
anywhere in function body acts as the statement is split into two and the declaration is moved to the top of the function
Coping mechanism: declare variables at the top
A coping mechanism exists for addressing variable hoisting. Only declare variables with
var at the top of a function. This way there will not be any surprises regarding hoisting.
ES6 let works more sanely
ES6 brings us two new keywords that are related to variable declaration:
const keyword is used for creating values that are only assigned once. The
let keyword is used for creating block scope variables (in contrast to
var creating a function scope variable).
A variable declared using the
keyword acts differently in the case of referencing the variable before it's initialized. Variable hoisting allows us to create code that references a variable before it is declared
here the declaration of
a is hoisted to top of the function and it gets assigned the value
undefined. A variable declared using
does get hoisted, but it will not get initialized but will produce an error if it is accessed without a value.
This eases us the approach of declaring variables at the top of a function, its no longer necessary for
- Using && and || outside of if-clause
to get lost with Node.js