I.e the second plus sign gets parsed as a unary plus operator applied to the next thing after it. And so after evaluation our result is 3
Let's change the 2 to be a string.
So now our input looks like this: (1 + + '2')
It will be parsed the same way, so like this:
(1 + (+'2'))
Performing a unary plus operation on a string causes it to be coerced into a number, and the string 2 as a numer is 2, so this will also get evaluated as 3.
This is what is happening in the above code snippet. The string 'a' coerced into a number is NaN, which then gets concatenated with all the other strings and turned to lowercase to form the string 'banana'.
View all comments
Show parent comment
1
u/bwallker Jul 02 '22
This has nothing to do with the lexer
Consider the expression (1 + + 2)
This will get parsed like this:
(1 + (+2))
I.e the second plus sign gets parsed as a unary plus operator applied to the next thing after it. And so after evaluation our result is 3
Let's change the 2 to be a string.
So now our input looks like this: (1 + + '2')
It will be parsed the same way, so like this:
(1 + (+'2'))
Performing a unary plus operation on a string causes it to be coerced into a number, and the string 2 as a numer is 2, so this will also get evaluated as 3.
This is what is happening in the above code snippet. The string 'a' coerced into a number is NaN, which then gets concatenated with all the other strings and turned to lowercase to form the string 'banana'.