Day 2 : Undefined and Hoisting - JavaScript
Undefined :
- As we all know JavaScript is a interpreted language i.e line by line compilation or JIT (just-in-time) compilation done here.
- When variable is declared but not defined or assigned any value then variable returns undefined value.
- The methods also returns undefined value when the variable declared for it does not have assigned value.
- Example for undefined type:
- Output :
- From above example we know that when JavaScript has no defined value for variable then it shows undefined.
- May you think that why it not shows error? It is because of hoisting.Hoisting is important concept in JavaScript which we will study later.
Is null and undefined are same?
- No, the null and undefined are two different entities in JavaScript.
- The Null is a value that can be assigned to variable and it "shows no value" where the variable is said to be Undefined if it is declared but "no value is assigned to it".
- The Null is the keyword in JavaScript which gives no value where as Undefined is global variable or type that JavaScript creates at run-time.
Hoisting :
- Hoisting is the important and default term in JavaScript.
- As in above undefined example we think that why it don't shows error?
It is because in JavaScript, when we declare any variable or function the compiler compiles it first and gives space for it in memory.
- In JavaScript, the declaration of variable and function only hoisted. The initialization is not hoisted.
- So we can say that, the declarations may at anywhere in program but at compilation time it compile first or moved at the top.
- Example 1:
alert(x);
// The output of above program is 2 because the variable is declared and initialized at first.
- Example 2:
alert(x);
x=2;
//In above example the x is declared at the top and initialized at bottom.So hoisting is occur on here and the output is undefined.
- Example 3:
alert(x);
var x;
//In above example the x is declared at bottom and initialized at first.But because of hoisting of declaration the output is 10.
Their is no any written code for hoisting it just like a magic in JavaScript.
- The above program shows undefined as an output because the x is declared first but initialized last or after alert message.
- So we come to know that JavaScript not hoist initialization.
Thank You!!!
For more understanding watch below video :
JavaScript Day 1 : Day 1
JavaScript Day 2 Global Pollution : Day 2 Global
Comments
Post a Comment