Hoisting in JS
Javascript is the strange of them all. If one is not familiar with hoisting, judging a result won't always be accurate. To know more about how javascript engines interpret the script, let's start with hoisting.
Hoisting is javascript's manner to arrange variable and function declarations at the top of the script. Because of this hoisting behaviour, we can call functions before they are declared.
printMessage('Hello World'); //Hello World function printMessage(msg){ console.log(msg); }
These variables and functions are not physically moved to the top of you code but actually put up in the memory.
For example, if you declare a variable with var in your script,
var x = 0 //declaration and assignment
This variable will be read by javascript in the following form
var x; //declaration on top x = 0; //assignment
Let's look into a more interesting example
... // your code logic console.log(x) ... var x = 0;
This code will run as:
var x; ... // your code logic console.log(x) // undefined ... x = 0;
Noticed how the x is UNDEFINED and not (ReferenceError: x is not defined), if you declare and assign a value to a variable later in your code but try to access the variable above, you wont be getting a reference error but instead be getting undefined because the value of x is not yet assigned, but the variable has been declared on the top because of the hoisting behaviour of Javascript.
One thing has to be noted here is that hoisting behaviour does not effect non declared variables or functions or those declared by let or const.
console.log(y) // Cannot access 'y' before initialization let y = 0;
console.log(z) // Cannot access 'z' before initialization
const z = 0;
console.log(a) // a is not defined
a = 0;
console.log(x) // undefined
var x = 0; console.log(x) //0
I hope the above example explains it all. and undefined and not defined are not same :p
Catalysing Business Success with AI Recruiting and Automation: Revolutionising Hiring Results and Garnering Acclaim from 100+ Industry Leaders
10 个月Aalishan, thanks for sharing!