Tom
Tom

Reputation: 4180

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?

Upvotes: 4

Views: 82

Answers (3)

Paul Butcher
Paul Butcher

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

Danilo Valente
Danilo Valente

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

Triode
Triode

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

Related Questions