Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Quiz #11

DZone's Guide to

JavaScript Quiz #11

Are you ready to decipher this short script that's overloaded with 'not' and 'double not' operators?

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

If you haven't checked out JavaScript quizzes 7, 8, 9, and 10 take some time to look at those after doing this one.  Each one builds on the other and they get progressively more difficult. Assume that we have the following JavaScript code:

<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.*


Answer:

The code will work fine. The alert will output 2. Let’s understand why.

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 evaluated to true.
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 2.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}