loading...

Understanding to Hoisting

edwardluu profile image Edward Luu ・2 min read

What is Hoisting?

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

Variable

Example of hoisting

console.log(A); // Returns undefined, as the only declaration was hoisted, no initialization has happened at this stage 

var A = 'edward';
Enter fullscreen mode Exit fullscreen mode

Explain for this one, the declare of A will push to the top of the current scope. But the value of A does not assign for now. See the code below.

var A; // Declaration
console.log(A); //Returns undefined, as only declaration was hoisted, no initialization has happened at this stage 
A = 'edward'; // Initialization
Enter fullscreen mode Exit fullscreen mode

The let and const Keywords

  • Variables defined with let and const are hoisted to the top of the block, but not initialized.

  • Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

  • Using a let or const variable before it is declared will result in a ReferenceError.

console.log(A); // Uncaught ReferenceError: Cannot access 'A' before initialization

let A = 'edward';

//const similar to let.
Enter fullscreen mode Exit fullscreen mode

Function

One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. For example:

displayName('Edward'); // My name is Edward 

function displayName(name) {
  console.log(`My name is ${name}`)
}
Enter fullscreen mode Exit fullscreen mode

Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in JavaScript.

Reference :
https://www.w3schools.com/js/js_hoisting.asp
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Discussion

pic
Editor guide