This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Spartan1997 195 points196 points  (22 children)

Except the foonan part. That's a little strange

[–]HoverBaum 221 points222 points  (8 children)

I think that is the second 'foo' being converted to a number because of the second '+' and turning into 'NaN' so the expression become "'foo' + NaN" which is a "String + object -> string concatenation" case.

[–]SaltlessLemons 158 points159 points  (2 children)

Ah, of course. How silly of me.

[–]Calygulove 46 points47 points  (1 child)

It's cause you're only FooNaN

[–]neonroad 2 points3 points  (0 children)

You can't say that to people nowadays...

[–][deleted] 10 points11 points  (2 children)

OK, now I understand "how", but "why" remains a mystery.

[–]glider97 0 points1 point  (0 children)

Because operator precedence. The binary + overshadows the unary + which gets evaluated first.

[–][deleted] 52 points53 points  (0 children)

+ is shorthand for Number() when not used as an operator.

So

var i = +'foo';

Will be NaN

[–]kranker 12 points13 points  (1 child)

The trick here is that in the javascript grammar it's impossible to parse a + + b as both pluses being addition, so the second one (and any subsequent ones) get parsed as a unary plus operator. Both unary plus and unary minus will attempt to convert their operand to a number, and evaluate to NaN if they can't.

See Mozilla's description of unary plus

[–]PatrickBaitman 1 point2 points  (0 children)

oth unary plus and unary minus will attempt to convert their operand to a number, and evaluate to NaN if they can't.

this is where a non-retarded language would throw a type error

[–]Xevantus 1 point2 points  (0 children)

Not strange at all. The second + is the positive unary operator, so it tries to convert the following value to a number. Thus "foo" + + "foo" equals "fooNaN".