Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NaN in Javascript string concatenation

Tags:

javascript

Take this array:

errors [
    "Your name is required.", 
    "An email address is required."
]

I am trying to iterate it and create a string like:

"Your name is required.\nAn email address is required.\n"

Using this code:

var errors = ["Your name is required.","An email address is required."];

if (errors) {

    var str = '';

    $(errors).each(function(index, error) {
        str =+ error + "\n";
    });

    console.log(str); // NaN

}

I am getting NaN in the console. Why is this and how do I fix it?

Thanks in advance.

like image 390
beingalex Avatar asked Jul 02 '14 15:07

beingalex


1 Answers

=+ is not the same as +=. First is x = +y and another is x = x + y.

+x is a shortcut for Number(x) literally converting the variable to number. If the operation can't be performed, NaN is returned.

+= acts like string concatenation when one of the parts (left or right) has a string type.

like image 149
VisioN Avatar answered Sep 22 '22 03:09

VisioN