Over a million developers have joined DZone.

JavaScript Quiz #11

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

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript

Published at DZone with permission of Hazem Saleh, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}