简体   繁体   中英

why does a variable in javascript seem to hold the value “undefined” even when it was defined

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?

var x = "";
x += "abc";
alert(x);

Try this. You are trying to add 'abc' and undefined which will result to undefinedabc .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM