Hoisting: ES6 Basics
Understanding Variable and Function Hoisting in ES6: A Look at Scope and Temporal Dead Zones
Hoisting is a JavaScript mechanism where variables and function declarations are moved, or rather, lifted (hoisted) to the top of their containing scope during the compile phase, before code execution. This means that you can use functions and variables before they have been declared in the code.
Variables:
In ES6, we have three ways to declare variables: var
, let
, and const
.
- var: It is function-scoped, and it will be hoisted to the top of its scope and initialized with
undefined
. - let and const: They are block-scoped, and they will also be hoisted to the top of their block, but they will not be initialized. If you try to access them before the declaration, you will get a
ReferenceError
.
Here’s a quick example to illustrate the difference:
function example() {
console.log(a); // undefined, as var variables are hoisted and initialized with undefined
var a = 5;
console.log(b); // ReferenceError, as let variables are hoisted but not initialized
let b = 10;
console.log(c); // ReferenceError, as const variables are hoisted but not initialized
const c = 20;
}
example();
Functions:
Function declarations are hoisted as well, and they are hoisted with their implementation. This means you can call a function before it has been defined in the code.
hello(); // Outputs: "Hello, World!"
function hello() {
console.log("Hello, World!");
}
However, function expressions are not hoisted like function declarations. If you try to call a function expression before it is defined, you will get a ReferenceError
.
someFunction(); // TypeError: someFunction is not a function
var someFunction = function() {
console.log("Hello, World!");
}
In summary, hoisting in ES6 involves lifting variable and function declarations to the top of their respective scopes during the compilation phase, but the way var
, let
, const
, and function expressions are hoisted differs. var
declarations are hoisted and initialized with undefined
, while let
and const
are hoisted but not initialized, leading to a ReferenceError
when accessed before declaration. Function declarations are fully hoisted with their implementation, but function expressions are not.