Why does case 1 give us :error: TypeError: x is undefined on line...
//case 1
var x;
x.push(x);
console.log(x);
Why does case 2 shows us Array[undefined] in console
//case 2
var x;
var x = [x];
console.log(x);
What is the difference between this 2 cases ?
4 Answers 4
To be able to push anything values to x
, you must first say that it is an array like this
var x = [];
About the variable is showing as undefined because any variable in javascript when no values is assigned to it is by default undefined.
Comments
In case one, the line x.push(x);
will throw an error if x
is not defined - you can't access properties of an undefined
object, of course.
In case two, x
is not defined at the point the line x = [x];
is run, but you aren't trying to access any properties of x
or anything like that - it's just an undefined
value, which is OK. So, the expression [x]
results in an array with one item, x
(which is undefined
), thus [undefined]
.
Comments
Case 1
You are trying to invoke .push()
on undefined
var x; // x is declared but value is undefined
x.push(x); // .push() can be invoked only on array types - that's why you get the error
console.log(x); // error happens before this line
Case 2
unndefined
is a value in JavaScript. You are creating an array with one entry - undefined
.
var x; // x is undefined
var x = [x]; // x = [undefined] - an array with one entry - undefined
console.log(x); // prints the array
Comments
There are somethings need to be explained:
- When you declare a variable,
undefined
is the default value is been set. Until you set any other likevar x = '';
. [].push()
is only available on arrays.
So, in your both cases:
Case: 1
var x; // default value set to = undefined
x.push(x); // here push is undefined because undefined don't have push method.
console.log(x); // it doesn't executes because of breaking line of code above.
Case: 2
//case 2
var x; // default value set to = undefined
var x = [x]; // now x is converted to an array and reassigned to x.
console.log(x); // logs array of one undefined value.
x
is undefined because it has no value.push()
is an array method, whiletypeof(x)
would return undefined. In case 2,x
is still undefined in the first declaration. In the second declaration, you're making it an array, but give it an undefined value.