Reputation: 55
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 ?
Upvotes: 1
Views: 179
Reputation: 74738
There are somethings need to be explained:
undefined
is the default value is been set. Until you set any other like var x = '';
.[].push()
is only available on arrays. So, in your both cases:
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
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.
Upvotes: 0
Reputation: 6299
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
Upvotes: 0
Reputation: 4013
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.
Upvotes: 3
Reputation: 371069
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]
.
Upvotes: 2