In the code below
var x = 1;
(function () {
console.log(x);
var x = 2;
}());
Why is it that when console.log(x), x is undefined?
This is because console. log() does not return a value (i.e. returns undefined). The result of whatever you entered to the console is first printed to the console, then a bit later the message from console. log reaches the console and is printed as well.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
You get undefined when you try to access the array value at index 0, but it's not that the value undefined is stored at index 0, it's that the default behavior in JavaScript is to return undefined if you try to access the value of an object for a key that does not exist.
The JavaScript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.
Variable hoisting. The actual code is executed like this.
var x = 1;
(function() {
var x; // x = undefined
console.log(x);
x = 2;
})();
Edit: On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):
"Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global."
Because of the compiler, even if you initiate a var down below the code, the compiler send it to the top, just like var x;
, so it first initiate as undefined "x" before running console.log, that's why is such a good practice to initate all vars you're going to use first thing in the function, so these mistakes won't happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With