Why does a variable in javascript seem to hold the value "undefined" even if it was defined

if I run the following javascript code, the browser warns "undefinedabc".

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

It seemed to me that I defined the variable x, so why does it look like undefined?

+4
source share
3 answers

undefined- The default value for any variable without an assigned value. So that var x;means a = undefined. When you add to it "abc", you do undefined + "abc". Finally, undefinedattached to "undefined"and then concatenated with "abc"and goes into "undefinedabc".

concat var x, (, JavaScript ):

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

MDN .

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

. 'abc' undefined, undefinedabc.

+5

, :

"Variables are initialised to undefined when created."

( , =).

, 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)"

, "abc" - , x String, ToString. x, , undefined.

, ToString, , undefined "undefined".

+1
source

Source: https://habr.com/ru/post/1527901/


All Articles