Have you heard of hoisting?, and might be wondering what it is right, or you probably got an error and they told you it was as a result of hoisting right?
Anyways I am here to get you through it.
PREREQUISITE KNOWLEDGE:
JavaScript is a synchronous single threaded language.
Synchronous means it executes code in the order in which they were placed on the script (from the top to bottom), it executes the code from line 1, then line 2 and so on.
Single threaded means it only does one thing at a time, it does not multitask, it fully executes a line of code before it continues to the next line, it cannot be executing the code in line 3 at the same time the code in line 4.
So in short, synchronous single-threaded means it executes one line of code at a time in the order they appear on the script (from top to bottom).
HOISTING is storing of variables and functions in the variable environment or memory of an execution context before execution.
Before JavaScript starts executing your code, it stores it memory first
1. Variables stored with “var” keywords are assigned “undefined” in memory during hoisting. Hence if you try to access them before they are executed you will get undefined.
NOTE: The debugger is turned on to pause to the code from executing at specific points so you can notice what happens within the code and the memory
Notice what is assigned to “a” in the global memory before the line var a = “JavaScript” was executed.
2. Variables stored with “const” and “let” keywords assigned “<value unavailable>” are stored in the Temporal Dead Zone (TDZ) , a separate section within the global memory. When you try to access them before they are executed, you get an error “ReferenceError: Cannot access ‘b’ before initialization”.
Notice variables “a” and “b” are saved in “Script” and not “Global” and they are assigned “<value unavailable>”. This only happens before line const b =”Hoisting” and let c = “John” are executed.
Classes are also hoisted like “const” and “let”. You cannot initialize a class before executing it else you will get an error
Example:
3. Functions are stored with a reference to the entire function code, hence you can invoke or access them before they are executed.
Notice here that the function labeled “arr” has been saved in memory before it is executed, the debugger is placed on the first line which means it pauses the code execution.
Hence you can easily use or print or invoke a function before it is executed in the next line of code.