Dewseph
Dewseph

Reputation: 155

Confusing JavaScript statement about string Concatenation

I was developing a node.js site and I made a copy and paste error that resulted in the following line (simplified for this question):

var x = "hi" + + "mom"

It doesn't crash and x = NaN. Now that i have fixed this bug, I am curious what is going on here, since if I remove the space between the + signs I get an error (SyntaxError: invalid increment operand)

My Question is : Can some explain to me what is going on in the statement and how nothing (a space between the + signs) changes this from an error to a NaN?

PS. I am not sure if this should go here or programers.stackoverflow.com. Let me know if I posted on the wrong site.

Upvotes: 3

Views: 152

Answers (1)

Evan Davis
Evan Davis

Reputation: 36592

It's being interpreted like this:

var x = "hi" + (+"mom")

The prefix + tries to coerce the string to a number. Number('mom') is NaN, so +'mom' is also NaN.

Upvotes: 7

Related Questions