JavaScript Quiz #11

Assume that we have the following short JavaScript code:

<script>
    var x = !!"Hello" + (!"world", !!"from here!!");
    
    alert(x);
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alert will output 2. Let’s understand why we will have this result.

The following sequence of operations occurs:
1. !!"Hello" ==> This operand will be evaluated to !false which will be finally true.
2. (!"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 will be evaluated to true.
3. As none of the operands is of String type, the + operands will be converted to number which means true + true will be evaluated to 1 + 1 which will equal finally 2.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha