Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 902
Tom Avatar asked Dec 20 '22 18:12

Tom


1 Answers

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.

like image 163
Danilo Valente Avatar answered May 04 '23 00:05

Danilo Valente