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?
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.
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