<script> var x = !!"Hello" + (!"world", !!"from here!!"); alert(x); </script>
Question: Will this code succeed or fail? And if it succeeds, what is the output of the alert?
*Write your answer on a piece of paper and then read the answer.*
The code will work fine. The alert will output
2. Let’s understand why.
The following sequence of operations occurs:
!!"Hello" ==> This operand will be evaluated to
!false which will be finally
(!"world", !!"from here!!") ==> The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand, which means that
!!"from here!!" will be returned and evaluated to
3. Since none of the operands are
String types, the
+ operands will be converted to numbers, which means
true + true will be evaluated to
1 + 1, which will equal finally