Execution Context –
1st phase (Creation) –
– Global Obj
– this
– Outer Environment
– Hoisting – functions are in memory, variables names are valid, but undefined
1 2 |
var a; console.log(a); |
output:
undefined
undefined
In JS, when we see undefined, its a special value that JS has which means the variable has not been set.
1 2 3 4 5 6 7 8 |
var a; console.log(a); if (a === undefined) { console.log('a is undefined!'); } else { console.log('a is defined'); } |
output:
a is undefined!
In the example below, you’ll get an error sayings its variable a is ‘not defined’ because after the JS compiler parses everything and put them into memory, it didn’t find anything for a variable named ‘a’.
Thus, when you try to access it in your execution phase, a does not exist.
1 2 3 4 5 6 7 |
console.log(a); if (a === undefined) { console.log('a is undefined!'); } else { console.log('a is defined'); } |
Never set yourself to ‘undefined’
1 |
a = undefined |
It’s better to let ‘undefined’ mean that the variable has NEVER been set. It should mean the developer has never touched it.