Hoisting
Hoisting
What is hositing ?
Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
-- mdn web docs
In simple terms, Hoisting
is a default behaviour in JavaScript that allows you to use functions or variables before they are declared in your code. For instance,
foo() // prints 'foo printed' in console
function foo(){
console.log('foo printed')
}
console.log(boo) // prints 'undefined' in console
var boo = 'boo'
Train of Thoughts
❓ Why is Hositing introduced in Javascript?
Brandan Eich's (creator of JavaScript) tweet summarized it 😂.
Function hoisting allows top-down program decomposition, 'let rec' for free, call before declare; var hoisting tagged along.
var
hoisting was thus [an] unintended consequence of function hoisting, no block scope, [and] JS as a 1995 rush job.
Given the benifit of hoisting, JavaScript Interpreter executes in a two-pass approach, details on JavaScript is executed under the hood can refer to this blog by Victor Ikechukwu.
Deep Dive
JavaScript creates all variables in the current scope before it even tries to executes the code, definition for different ways of declaring variables, however, are different in ECMAScript.
A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Environment Record is instantiated and are initialized to undefined when created.
-- ECMAScript
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
-- ECMAScript
Declaraion Hoisted | Initialization Hoisted | Access before initialization | Temporal Dead Zone | |
---|---|---|---|---|
var | ✅ | ❌ | undefined | ❌ |
let | ✅ | ❌ | ReferenceError | ✅ |
const | ✅ | ❌ | ReferenceError | ✅ |
function declaration | ✅ | ✅ | ✅ | ❌ |
class | ✅ | ❌ | ReferenceError | ✅ |
import | ✅ | ✅ | ✅(Side effect included) | ❌ |