Liglo App
Liglo App

Reputation: 3819

Inconsistent behavior of JavaScript's + operator

Why does this

2 + + 3

return 5, but this

'2837363' + + '/'

returns

"2837363NaN"? Even the '/' got lost.

Why would a programming language accept this syntax without throwing a syntax error? When does it assume, the empty place evaluates to 0 (1st example) and when to NaN (2nd example)?

Upvotes: 0

Views: 51

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

Prepending a variable with a + implies type coercion to a number type.

+ 5 => 5
+ '5' => 5
+'a' => NaN
+'/' => NaN

When you do +'/' the result is NaN

Upvotes: 4

Related Questions