Hoisting
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.
Again: move the declaration of
Functions
Variables
Classes
Imports
Hoisting Behaviors:
You can access its value even before the line where it's declared like -> Value hoisting (e.g
function
declaration)catfather(); function catfather(){ console.log('hey meiow') }
You can reference the variable before its declaration line without errors, but its value will be 'undefined' until the actual declaration -> Declaration hoisting (e.g
var
){ console.log(cat); // hoisted but undefined } { var cat= 9; } console.log(cat) // output is 9
The variable’s declaration affects its scope even before the line where it’s declared. like
let
,const
andclass
declaration -> lexical declarations. Accessing the variable before its declaration throws an error because of the Temporal Dead Zone (TDZ). The variable exists but is unusable until declared.//Example 1 console.log(cat); // js throw a ReffrenceError here! let cat = 9; // js dosen't read here beacuse of error in line 1 console.log(cat); // js dosen't read here beacuse of error in line 1
// Example 2 let cat = 2; { console.log(cat); // js throw a ReffrenceError here! // Why? because "const cat" hoisted in the scope. so it makes a TDZ // after "{" until the below line that we declareded it; // Hint for CTF is here, find your solution with this. const cat = 1; }
// Example 3 { let cat = 3; } console.log(cat); // Uncaught ReferenceError: cat is not defined // Why? because let cat hoisted in its scope!
Side-effect hoisting happens before the main code. you’ll see the effects of some declarations (like
import
) before anything else runs.console.log(cat); // it will run if cat variable is exist in cat.js import cat.js; // Hoist then run.
Last updated