My JavaScript quiz – answers
Earlier this week, I posted my JavaScript quiz, containing some basic code along with questions. Here are the answers.
Example #1
var num1 = 5,
num2 = 10,
result = num1+++num2;
The key to understanding this example is to understand operator precedence. Clearly, +++ isn’t a valid operator, so the JavaScript engine breaks it up into a postfix increment operator and the plus sign. This code is completely valid and parses without problem, but really could be written like this:
var num1 = 5,
num2 = 10,
result = num1++ + num2;
With the understanding that this is how the code is interpreted, the questions should be fairly easy.
- What is the value of
result? The value is 15 because the postfix increment works after thenum1+++num2statement has executed. - What is the value of
num1? The value is 6 because it is incremented after the last statement. - What is the value of
num2? The value is 10 because no operation takes place onnum2itself.
Example #2
var x = 5,
o = {
x: 10,
doIt: function doIt(){
var x = 20;
setTimeout(function(){
alert(this.x);
}, 10);
}
};
o.doIt();
The key to this example is understanding JavaScript scope. The alert inside of the closure references this.x, but because this reference is wrapped in a couple of functions inside of an object, what is the correct scope? The answer is pretty simple. All functions passed into setTimeout() are executed in the global scope.
- What value is displayed in the alert? The value is 5 because
this.xis the same aswindow.xandvar x = 5is equivalent towindow.x = 5.
Example #3
var num1 = "10",
num2 = "9";
The code is pretty self-explanatory, just two string variables being defined.
- What is the value of
num1 < num2? When both operands are strings, comparison operators perform string comparisons by comparing characters in the same position. The string “10″ comes before the string “9″ because the character “1″ comes before the character “9″ in ASCII. Since there are no more characters to compare after that point, this comparison is the one that remains. Thus, the value ofnum1 < num2istrue. - What is the value of
+num1 < num2? The plus operator here convertsnum1into a number, so now you’re comparing a number to a string. When this happens, the string operator gets converted into a number and then the comparison commences. So ultimately this is equivalent to 10 < 9, which very obviously isfalse. - What is the value of
num1 + num2? Both operands are strings, which means a string concatenation happens. The result is"109". - What is the value of
+num1 + num2? As you saw earlier, the plus operator converts a string to number, sonum1becomes the number 10. However, when the plus operator is used with a number and a string, the number gets converted to a string and then string concatenation is performed. So the result of this is the same as if you didnum1 + num2as the value is"109".
Example #4
var message = "Hello world!";
Just a simple string variable, nothing fancy here.
- What is the value of
message.substring(1, 4)? The first argument is the index of the first character you want and the second argument is the index of the character after the last one you want. In this case, you want the second character (index 1) through the fourth character (index 3). So the result is “ell”. - What is the value of
message.substr(1,4)? The first argument is the index of the first character you want and the second argument is how many characters to retrieve. In this case, you want the second character (index 1) and then three more characters, so the result is “ello”.
Example #5
var o = {
x: 8,
valueOf: function(){
return this.x + 2;
},
toString: function(){
return this.x.toString();
}
},
result = o < "9";
alert(o);
This is perhaps the most difficult of the code examples because you need to understand how valueOf() and toString() work. All objects have these two methods as they are defined on Object.prototype and inherited through the prototype chain (nitpickers will note that it’s possible to have objects that don’t inherit from Object, but I’m trying to keep this simple). These two methods get called behind-the-scenes all the time. The valueOf() method is called whenever comparisons are done and toString() is called whenever automatic conversion into a string is necessary. By overriding these methods, you can control the values they return in various circumstances.
- What is the value
result? ThevalueOf()method gets called behind-the-scenes here, so really the comparison is 10 < “9″. As you learned earlier, a comparison between a number and a string causes the string to be converted into a number, so the comparison ends up being 10 < 9, which isfalse. - What is the value displayed in the alert? Values passed into
alert()are converted to strings, which means thattoString()gets called. The alert, therefore, displays"8".
That’s it!
I hope you’ve enjoyed this little JavaScript quiz and hopefully learned a thing or two.
Update (18-Feb-2010): Fixed typo in answer #1.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.




12 Comments
Thanks for the explanations! In #1 the 2nd question’s correct answer is 6, not 16 I think.
Adam Brunner on February 18th, 2010 at 9:16 am
Shouldn’t num1 be 6 in Example 1?
Jörn Zaefferer on February 18th, 2010 at 9:56 am
Great quiz and good explanations! =)
Anton on February 18th, 2010 at 10:30 am
I think there is typo in this statement
What is the value of num1? The value is 16 because it is incremented after the last statement.
it should be 6 instead of 16.
rnella01 on February 18th, 2010 at 10:52 am
I enjoyed this quiz much more than the other one that was floating around the web a couple weeks ago. It’s much more real world.
Jeffrey Way on February 18th, 2010 at 2:58 pm
[...] 本文ä¸è®¨è®º1+1为何ç‰äºŽ2,也ä¸ä»‹ç»JavaScriptä¸åŠ å‡ä¹˜é™¤ä¸å¤§å®¶éƒ½çŸ¥é“的事。è¦è¯´ï¼Œå’±å°±è¯´ç‚¹ç‰¹åˆ«çš„。就ç€Zakas大å”给咱出的题http://www.nczonline.net/blog/2010/02/18/my-javascript-quiz-answers/,首先咱æ¥çœ‹ä¸€ä¸‹ï¼Œè¿ç®—符的优先级。 [...]
JavaScript è¿ç®—符 | å°å°å,simaopig on February 22nd, 2010 at 6:43 am
Thanks for a great fun quiz..
The #1 result = num1+++num2 . I first thought it was broken down like this num1 + (++num2) ..turned out to be (num1++) + num2.
If possible, could you explain more on why it’s not the other way around ?
Thanks,
Totti
tot2ivn on February 27th, 2010 at 1:22 am
P/S: is that because increment ++ has higher precedence level than plus + ?
tot2ivn on February 27th, 2010 at 1:26 am
they are defined on Object.prototype an inherited through the prototype chain
in your article, maybe you missed a “d”, I guess you would write like this:
they are defined on Object.prototype an(d) inherited through the prototype chain
^_^
rainoxu on March 1st, 2010 at 7:34 am
Perfect! Thanks, so many things to learn for me in this quiz and your answers.
Omid on March 23rd, 2010 at 2:21 pm
Awesome, this quiz is definitely an eye opener. #2 got my, thinking that a prefix of var would save me, but didnt.
Cheers!
GafroNinja on April 26th, 2010 at 6:42 am
oops type. that would be “#2 got me, thinking…”
GafroNinja on April 26th, 2010 at 6:42 am
Comments are automatically closed after 14 days.