Reputation: 4180
if I run the following javascript code, the browser alerts "undefinedabc".
var x;
x += "abc";
alert(x);
To me it looked like I did define the variable x, so why does it seem to be undefined?
Upvotes: 4
Views: 82
Reputation: 6956
First examine the behaviour of a Variable Statement, Specifically:
"Variables are initialised to undefined when created."
Then examine the behaviour of the addition operator (compound assignment applies the behaviour of the operator corresponding to what precedes =
).
Specifically, point 7:
"If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)"
So, since "abc"
is a string, x
is to be translated to a String, according to ToString. x, as we know from above, is undefined.
Finally, examine the behaviour of the abstract operation ToString, specifically, that an undefined argument results in the string "undefined".
Upvotes: 1
Reputation: 11342
undefined
is the default value of any variable with no value assigned. So, var x;
means that a = undefined
. When you add "abc"
to it, you're actually doing undefined + "abc"
. Finally, undefined
is stringifiend to "undefined"
and then concatenated to "abc"
and turns to "undefinedabc"
.
In order to concat initialize the var x
, you should assign an empty string to it (remember that JavaScript dinamically-typed):
var x = '';
x += "abc";
alert(x); // "abc"
This MDN article describes this behaviour.
Upvotes: 5
Reputation: 11359
var x = "";
x += "abc";
alert(x);
Try this. You are trying to add 'abc'
and undefined
which will result to undefinedabc
.
Upvotes: 5