What It Will Print Console.log(1+ + "2")
Why does this JavaScript statement: console.log(1 + + '2'); print 3 as the output? I am not sure why it's printing this - I expected '12'.
Solution 1:
+ or - operand in front of a string converts it to number. so here +"2" will become 2 hence the result will be 3.
=> 1 + + "2" // +"2" = 2
=> 1 + 2
=> 3
If you use - in between like
=> 1 - - "2" // -"2" = -2
=> 1 - - 2 // 1 - (-2)
=> 1 + 2
=> 3
So,
-"2" ==> -2
+"2" ==> 2
+"Hello" ==> NaN
-"Hello" ==> NaN
Solution 2:
console.log(1 + "2") prints 12 as + acts as an concatenation operator.
But if you try to print console.log( + "2" ) you will get output as 2 coz it is casted as an integer.
Therefore console.log( 1 + +"2" ) will give you result as 3
Solution 3:
Regarding the specific output of
console.log(1 + + "2");
Run it on your browser console. The better question is why does it output what it does -
console.log(1 + + "2");
^
That is the binary + operator, which will concatenate strings or add numbers.
console.log(1 + + "2");
^
That one is the unary + operator, which converts "2" to a number.
Don't create JavaScript like this. It's confusing.
Post a Comment for "What It Will Print Console.log(1+ + "2")"