What is JavaScript hoisting?
Hoisting is a concept specific to JavaScript. JavaScript moves all declarations to the top as a default behavior.
Let’s see some examples to understand the context and possible issues that hoisting might cause.
Variable Hoisting:
x=1;
console.log(“x =”+x); // logs x =1
var x; // declaration at the bottom moves to the top
The declaration of variable x at the bottom moves to the top, giving us the value 1 in alert instead of undefined.
Can you guess the output of below example?
x=1;
console.log(“x = ”,x); // logs x = 1
var x = 5; //initialization vs declaration
console.log(“x = ”,x); // logs x = 5
1 and 5 that’s right!
Hoisting only happens with declarations but not with initializations
That means, if you execute below code, you will get Uncaught ReferenceError: x is not defined
console.log(“x = “,x); // Throws Uncaught ReferenceError
x = 6; // initialization
How do we make sure we don’t write code with unusual behaviors?
strict, const and let to the rescue!
You can add “use strict;” in the first line of JS code to make sure a variable is always declared before using it.
//With strict keyword"use strict";
x = 1;
console.log("x = ",x); //ReferenceError: x is not defined----------------------------------------------------------// Without strict keyword
x = 1;
console.log("x = ",x); // logs x = 1----------------------------------------------------------// Using let
x = 1;
console.log("x = ",x); // Cannot access 'x' before initialization
let x;
Function hoisting:
Hoisting also applies to functions in JavaScript. You can invoke a function even before declaring it.
printX(1); // logs x = 1// function declaration gets hoisted to the topfunction printX(val) {
console.log("x =" , val);
}
How can we stop hoisting of functions? by using function expressions!
printMe(1); // printMe is not a function//declare function using function expression
var printMe = function printX(val) {
console.log("x =" , val);
}
Variable and Function hoisting:
There is an order of precedence that applies to hoisting if you are using a variable and function with same name.
- Variable initialization takes precedence over function declaration.
var printX = 0; // initialization
function printX(val) {
console.log("x =" , val);
}
console.log("printX",printX) // logs 0printX(3) // Error: printX is not a function
- Function declarations take precedence over variable declarations.
var printX; // declaration
function printX(val) {
console.log("x =" , val);
}
console.log("printX",printX) // logs [Function: printX]
printX(3) // logs x = 3
I hope the last example was convincing enough for you to start declaring variables and functions before using them or leverage let and const. 😃