3

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.

5
  • 1
    In Firefox this results to "hiNaN", which is reasonable. Commented Dec 17, 2014 at 20:47
  • My complete guess is the whitespace is interpreted as 0 or something? ---- scratch that. Its the result of "hi" + (+ "mom") I guess (+ "mom") is interpreted as positive "mom" and therefore NaN. Commented Dec 17, 2014 at 20:48
  • @Sirko Thank you for your quick response. The fact that it is coming back as NaN (or "hiNaN") is reasonable. I am just curious how is it getting to NaN instead of crashing. What javascript quark is this doing? Commented Dec 17, 2014 at 20:52
  • @AlexeyLebedev Thank you for answering, but could you explain your comment a little more please? Commented Dec 17, 2014 at 20:52
  • 1
    In a + + b, you have the addition operator and the unary + operator. More info here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 17, 2014 at 20:58

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"parseFloat('mom') is NaN, so +'mom' is also NaN." Rather "Number('mom') is NaN, so +'mom' is also NaN." Because parseFloat('5foo') is 5, but +'5foo' is still NaN.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.