You may have heard of JavaScript "hoisting" variables in a function, but you're not sure what it means. You'd like to be sure, so you don't make any mistakes related to variable declarations.

"What does variable hoisting mean?"

Variable hoisting is one of JavaScript's idiosyncracies but it has a coping strategy and also upcoming pain relief in ES6.

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

1 2 3 4 5 function fn ( ) { var a; console .log( 'hello world' ); var b; }

when run is interpreted by JavaScript as

1 2 3 4 5 function fn ( ) { var a; var b; console .log( 'hello world' ); }

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

1 var string = "abc" ;

anywhere in function body acts as the statement is split into two and the declaration is moved to the top of the function

1 2 3 4 5 var string; string = "abc" ;

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.

1 2 3 4 5 function fn ( ) { }

ES6 let works more sanely

ES6 brings us two new keywords that are related to variable declaration: const and let . The 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 let 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

1 2 3 4 function fn ( ) { console .log( 'variable a is: ' + a); var a = "abc" ; }

here the declaration of a is hoisted to top of the function and it gets assigned the value undefined . A variable declared using let does get hoisted, but it will not get initialized but will produce an error if it is accessed without a value.

1 2 3 4 function fn ( ) { console .log( 'variable a is: ' + a); let a = "abc" ; }

This eases us the approach of declaring variables at the top of a function, its no longer necessary for let -declared variables.

Related articles