What is hoisting?
When variables are encountered during the program run, during the first pass they are given space in memory and initialized with undefined
The variables are updated with their actual values only when the thread of execution reaches the line of code, where they are initialized.
So effectively during hoisting we feel as if the variables are "hoisted" to the top, but actually during the first pass, all variables are assigned undefined and stored in memory.
What is hoisted?
Although all three types of declaration, let, const and var are hoisted, var behaves differently from let and const. var declarations are initialized with undefined, but let and const are not initialized with a default value, instead an exception will be thrown when we try to access let and const before its initialization from the thread of execution inside from the source file.
// The first pass occurs and thread of execution starts from here // Here vx stores undefined var dev = "dev" // vx now stores "dev"
// The first pass is over // Here the Engine knows about cx and lx, but cannot assign a value to them const cx = 'dev' // now cx has its value as 'dev' const lx = 'dev' // now lx has its value as 'dev'
Temporal Dead Zone
// Line 1, here Engine knows about x, but not its value, start of temporal dead zone . . . let x = 'dev' // After assigning x some value, temporal dead zone is over, as its declaration is complete
- undefined refers to something that doesn't exist yet, or doesn't exist anymore
- null refers to an empty value
- reference error refers to an exception in which, let or const is accessed before its declaration is complete
To get a video tutorial on the concept
Top comments (0)