Javascript Interview 101: Hoisting in Javascript.

Javascript Interview 101: Hoisting in Javascript.

·

1 min read

Hoisting in Javascript's default behavior of moving declarations to the top of the current scope.

Example 1:

x = 5 
console.log(x); // return 5
var x; // declaration part

Expand: Hoisting in JS is the behavior of JS when it will move all declarations to the top of the current scope.

The example 1 will be run like this:

var x; 
x = 5; 
console.log(x) // return 5.

With the Javascript var keyword, the variable can be initialized before it declaration but with the let and const keywords is different.

If we use variables defined by var before it declaration, the default value with be undefined.

Variables defined with let and const are hoisted on the top of the current scope but not initialized.

x = 5;
console.log(x); 
// return ReferenceError: cannot access before initialized.
let x;

Advise: Declare your variables at the top.

Hoisting is an unknow or overlooked behavior of Javascript.

If a dev doesn't understand hoisting, programs may contain bugs (errors)

To avoid bugs, always declare all variables a the beginning of every scope.