Answering Baranovskiy’s JavaScript quiz
Last week, I tweeted about a JavaScript quiz I came across on Dmitry Baranovskiy’s blog entitled, So you think you know JavaScript? As with other quizzes of this type, there is only one question to answer for five different pieces of example code: what is the result? The example code tests some of the quirkier attributes of JavaScript engine behavior. I’ve seen similar quizzes in the past, sometimes by people saying that they use it as a test during job interviews. I think doing so is both disrespectful to the candidate as well as generally useless. You don’t encounter this type of quirk every day, so making that the minimum to get a job is about as useful as asking flight attendant candidate to explain jet propulsion.
Still, I liked some of the example code in this post because it can be used to explain some interesting things about JavaScript as a language. The following is an in-depth explanation of what is happening in each of those examples.
Example #1
if (!("a" in window)) {
var a = 1;
}
alert(a);
This strange looking piece of code seems to say, “if window doesn’t have a property ‘a’, define a variable ‘a’ and assign it the value of 1.” You would then expect the alert to display the number 1. In reality, the alert displays “undefined”. To understand why this happens, you need to know three things about JavaScript.
First, all global variables are properties of window
. Writing var a = 1
is functionally equivalent to writing window.a = 1
. You can check to see if a global variable is declared, therefore, by using the following:
"variable-name" in window
Second, all variable declarations are hoisted to the top of the containing scope. Consider this simpler example:
alert("a" in window);
var a;
The alert in this case outputs “true” even though the variable declaration comes after the test. This is because the JavaScript engine first scans for variable declarations and moves them to the top. The engine ends up executing the code like this:
var a;
alert("a" in window);
Reading this code, it makes far more sense as to why the alert would display “true”.
The third thing you need to understand to make sense of this example is that while variable declarations are hoisted, variable initializations are not. This line is both a declaration and an initialization:
var a = 1;
You can separate out the declaration and the initialization like this:
var a; //declaration
a = 1; //initialization
When the JavaScript engines comes across a combination of declaration and initialization, it does this split automatically so that the declaration can be hoisted. Why isn’t the initialization hoisted? Because that could affect the value of the variable during code execution and lead to unexpected results.
So, knowing these three aspects of JavaScript, re-examine the original code. The code actually gets executed as if it were the following:
var a;
if (!("a" in window)) {
a = 1;
}
alert(a);
Looking at this code should make the solution obvious. The variable a
is declared first, and then the if
statement says, “if a
isn’t declared, then initialize a
to have a value of 1.” Of course, this condition can never be true and so the variable a remains with its default value, undefined
.
Example #2
var a = 1,
b = function a(x) {
x && a(--x);
};
alert(a);
This code looks far more complex than it actually is. The result is that the alert displays the number 1, the value to which a was initialized. But why is that? Once again, this example relies on knowledge of three key aspects of JavaScript.
The first concept is that of variable declaration hoisting, which example #1 also relied upon. The second concept is that of function declaration hoisting. All function declarations are hoisted to the top of the containing scope along with variable declarations. Just to be clear, a function declaration looks like this:
function functionName(arg1, arg2){
//function body
}
This is opposed to a function expression, which is a variable assignment:
var functionName = function(arg1, arg2){
//function body
};
To be clear, function expressions are not hoisted. This should make sense to you now, as just with variable initialization, moving the assignment of a value from one spot in code to another can alter the execution significantly.
The third concept that you must know to both understand and get confused by this example is that function declarations override variable declarations but not variable initializations. To understand this, consider the following
function value(){ return 1; }
var value;
alert(typeof value); //"function"
The variable value
ends up as a function even though the variable declaration appears after the function declaration. The function declaration is given priority in this situation. However, throw in variable initialization and you get a different result:
function value(){ return 1; }
var value = 1;
alert(typeof value); //"number"
Now the variable value
is set to 1. The variable initialization overrides the function declaration.
Back to the example code, the function is actually a function expression despite the name. Named function expressions are not considered function declarations and therefore don’t get overridden by variable declarations. However, you’ll note that the variable containing the function expression is b
while the function expression’s name is a
. Browsers handle that a differently. Internet Explorer treats it as a function declaration, so it gets overridden by the variable initialization, meaning that the call to a(--x)
causes an error. All other browsers allow the call to a(--x)
inside of the function while a is still a number outside of the function. Basically, calling b(2)
in Internet Explorer throws a JavaScript error but returns undefined
in others.
All of that being said, a more correct and easier to understand version of the code would be:
var a = 1,
b = function(x) {
x && b(--x);
};
alert(a);
Looking at this code, it should be clear that a
will always be 1.
Example #3
function a(x) {
return x * 2;
}
var a;
alert(a);
If you were able to understand the previous example, then this one should be pretty simple. The only thing you need to understand is that function declarations trump variable declarations unless there’s an initialization. There’s no initialization here, so the alert displays the source code of the function.
Example #4
function b(x, y, a) {
arguments[2] = 10;
alert(a);
}
b(1, 2, 3);
This code is a bit easier to understand as the only real question you must answer is whether the alert displays 3 or 10. The answer is 10 in all browsers. There’s only one concept you need to know to figure out this code. ECMA-262, 3rd Edition, section 10.1.8 says about an arguments
object:
For each non-negative integer,
arg
, less than the value of thelength
property, a property is created with nameToString(arg)
and property attributes{ DontEnum }
. The initial value of this property is the value of the corresponding actual parameter supplied by the caller. The first actual parameter value corresponds toarg
= 0, the second toarg
= 1, and so on. In the case whenarg
is less than the number of formal parameters for theFunction
object, this property shares its value with the corresponding property of the activation object. This means that changing this property changes the corresponding property of the activation object and vice versa.
In short, each entry in the arguments
object is a duplicate of each named argument. Note that the values are shared, but not the memory space. The two memory spaces are kept synchronized by the JavaScript engine, which means that both arguments[2]
and a
contain the same value at all times. That value ends up being 10.
Example #5
function a() {
alert(this);
}
a.call(null);
I actually considered this to be the easiest of the five examples in this quiz. It relies on understanding two JavaScript concepts.
First, you must understand how the value of the this
object is determined. When a method is called on an object, this
points to the object on which the method resides. Example:
var object = {
method: function() {
alert(this === object); //true
}
}
object.method();
In this code, this
ends up pointing to object
when object.method()
is called. In the global scope, this
is equivalent to window
(in browsers, in non-browser environments it’s the global
object equivalent), so this
is also equal to window
inside of a function that isn’t an object property. Example:
function method() {
alert(this === window); //true
}
method();
Here, this
ends up pointing to the global object, window
.
Armed with this knowledge, you can now tackle the second important concept: what call()
does. The call()
method executes a function as if it were a method of another object. The first argument becomes this
inside the method, and each subsequent argument is passed as an argument to the function. Consider the following:
function method() {
alert(this === window);
}
method(); //true
method.call(document); //false
Here, the method()
function is called such that this
will be document
. Therefore, the alert displays “false”.
An interesting part of ECMA-262, 3rd edition describes what should happen when null
is passed in as the first argument to call()
:
If
thisArg
isnull
orundefined
, the called function is passed the global object as the this value. Otherwise, the called function is passedToObject(thisArg)
as the this value.
So whenever null
is passed to call()
(or its sibling, apply()
), it defaults to the global object, which is window
. Given that, the example code can be rewritten in a more understandable way as:
function a() {
alert(this);
}
a.call(window);
This code makes it obvious that the alert will be displaying the string equivalent of the window
object.
Conclusion
Dmitry put together an interesting quiz from which you can actually learn some of the strange quirks of JavaScript. I hope that this writeup has helped everyone understand the details necessary to figure out what each piece of code is doing, and more importantly, why it’s doing so. Again, I caution against using these sort of quizzes for job interviews as I don’t think they serve any practical use in that realm (if you’d like to know my take on interviewing front-end engineers, see my previous post).
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.
23 Comments
Wow, excellent post. Really great stuff. Love learning new things about JavaScript.
Question… why does JavaScript “hoist” variable declarations? I understand why it couldn’t “hoist” the initialization, and I also understand why it must “hoist” function declarations… but it seems weird to me that it must also “hoist” variable declarations. I can’t think of a reason why this is required behavior, it seems wrong/backwards to me.
Kyle Simpson on January 26th, 2010 at 1:46 pm
That’s probably a question best answered by folks from ECMA. I can only guess that it was a side effect of not supporting block-level variable scoping. Thinking through it, I could see implementers saying that without block-level variable scoping, they could pre-calculate the space necessary for all variables in a given function via variable hoisting. Perhaps that was an idea designed to simplify implementation.
Nicholas C. Zakas on January 26th, 2010 at 1:54 pm
Variable “hoisting” is basically a byproduct of the ECMAScript scoping rules, by scoping to a function rather than a block (as other languages do), it becomes very difficult to define “sensible” behaviour without just requiring all declared variables to be “live” for the entire function.
In reality of course ES has this behaviour because the first implementations (back before ES “existed”, when JavaScript and JScript were technically distinct languages) had this behaviour, and websites came to depend on it.
Oliver on January 26th, 2010 at 2:10 pm
Additional ECMA-262 5th edition references for example 1-3:
Page 59 – 10.5 Declaration Binding Instantiation and Page 87 – 12.2 Variable Statement
Also for JScript and other Function expression gotchas check out Juriy Zaystev’s post:
http://yura.thinkweb2.com/named-function-expressions/
John-David Dalton on January 26th, 2010 at 2:35 pm
Great post. This was a great read.
Ever thought of making a book of your blog posts?
Amit Behere on January 26th, 2010 at 2:44 pm
@John-David – Thanks, great references!
@Amit – A lot of the material in my blog posts end up in one or more of my books eventually.
Nicholas C. Zakas on January 26th, 2010 at 3:47 pm
[...] 今天Zakas专门撰文解ç”äº†è¿™å‡ é“题(http://www.nczonline.net/blog/2010/01/26/answering-baranovskiys-javascript-quiz/)。ä¸æ„§æ˜¯å¤§å¸ˆï¼Œå¾ˆæ·±åˆ»ã€‚ [...]
Zakas解ç”Baranovskiyçš„JavaScriptå°æµ‹è¯• « Kejun’s Blog on January 27th, 2010 at 12:25 am
[...] 测试结果还满æ„å—?看看zakas的详细解ç”,讲解很深刻哦! http://www.nczonline.net/blog/2010/01/26/answering-baranovskiys-javascript-quiz/ [...]
å‡ ä¸ªå°æµ‹è¯•,ç†è§£JavaScript作用域 | Javascript森林 on January 27th, 2010 at 1:27 am
Great writeup and excellent explanation. It’s definetly a bookmark.
I appreciate the effort you put into explaining the quirks hidden in the documentation.
Ionut Popa on January 27th, 2010 at 7:27 pm
[...] 這是 Nicholas C. Zakas 回ç”å…ˆå‰ Dmitry Baranovskiy 在他的 blog 上出的五é“æª¢è¦–ä½ æ˜¯ä¸æ˜¯çœŸçš„çžè§£ javascript çš„å°æ¸¬é©—。主è¦å°±æ˜¯åœ¨ javascript 的行為和 scope/closure 的觀念下出五é“題,並希望大家能在ä¸åŽ» console è·‘çµæžœçš„å‰æ下看看自己是ä¸æ˜¯çœŸçš„知é“會 alert 出些什麼æ±è¥¿ã€‚我覺得很ä¸éŒ¯æ‰€ä»¥å°‡ä»–的原文在這邊翻è¯ä¸€ä»½ä¸æ–‡ç‰ˆã€‚本文開始: [...]
Answering Baranovskiy’s JavaScript quiz « Linmic之雜亂記事 on January 28th, 2010 at 3:10 am
Great work as usual Nicholas. Simple way to explain some counterintuitive quirks of the language.
Michael Lee on January 29th, 2010 at 2:45 am
[...] 在Answering Baranovskiy’s JavaScript quiz一文ä¸ç»™å‡ºçš„å‰3个问题å‡ä¸Žé¢„解æžç›¸å…³ï¼Œå¦‚下: [...]
Javascript预解æžç›¸å…³ä¸€åˆ™ @ Miller on January 31st, 2010 at 4:30 am
[...] was recently reminded about Dmitry Baranovsky’s Javascript test, when N. Zakas answered and explained it in a blog post. First time I saw those questions explained was by Richard Cornford in comp.lang.javascript, [...]
Perfection kills » Javascript quiz on February 8th, 2010 at 3:14 pm
[...] was recently reminded about Dmitry Baranovsky’s Javascript test, when N. Zakas answered and explained it in a blog post. First time I saw those questions explained was by Richard Cornford in comp.lang.javascript, [...]
Ajaxian » Think You Know Javascript? Try this Quiz! on February 9th, 2010 at 4:49 am
If, like me, you first had a go at testing these using the javascript: URL pseudoprotocol please keep in mind that you’ll be playing with a global scope that can and will be ‘contaminated’ by whichever page you have open. So don’t be surprised if, when testing that first example in a browser window loaded with google.com, it returns 1. Turns out Google use window.a for something.
Adriano Castro on February 9th, 2010 at 8:36 am
[...] time’. Link here. Another interesting post explaining this javascript test offers some great insights into the workings of ECMA / [...]
how to interview for positions with heavy javascript development and advanced javascript tests | frag (frăg) on February 9th, 2010 at 9:48 am
Bleh. This is why I don’t like Javascript!
Matt Calthrop on February 9th, 2010 at 10:43 am
[...] a couple of JavaScript quizzes floating around. There was one by Dmitry Baranovskiy (for which I explained the answers) and one by Kangax. But there are so many strange pieces of JavaScript that I thought [...]
My JavaScript quiz | NCZOnline on February 16th, 2010 at 9:01 am
Regarding example 3, you wrote:
Identifier
a
holds a functional value because the function declaration replaces the value ofa
.(function(){
aaa = function(){ alert(1); };
function aaa(){alert(2);}
var aaa;
return aaa;
})()();
Would be equivalent to:
(function(){
var aaa;
function aaa(){alert(2);}
aaa = function(){ alert(1);}
return aaa;
})()();
An assignment expression anywhere would replace the value of
a
but that is beside the point.Regarding Example 4:
Assigning to formal parameters in Safari 2 does not update the
arguments
object. That is a bug of Safari.I don’t think it is disrespectful to ask such questions in an interview. Such questions can demonstrate the candidate’s ability to “be the interpreter”.
“being the interpreter” is a valuable skill. Being able to look at a piece of code and know exactly how it should run, and knowing implementation bugs (like the Safari 2 bug and the jscript bugs mentioned) is valuable.
I find this sort of question far more pertinent to the questions such as unrelated CS questions or problem solving questions. Writing a merge sort or BigInteger or general “problem solving” hypothetical questions are not the type of problems that a web programmer will be solving on a daily basis.
For those interested in unmoderated (free) discussion, this sort of subject matter is frequently discussed on comp.lang.javascript.
Garrett on February 17th, 2010 at 4:29 am
[...] arguments object and you saw that the corresponding named argument changed in value as well (see my writeup for more info). The opposite, however, is not [...]
Answering Soshnikov’s quiz | NCZOnline on February 23rd, 2010 at 9:01 am
For me, the key insight from these examples is that the order statements are presented in code by the programmer cannot be assumed to be the order they are executed.
And I agree 100% that one’s ability to code intelligently is totally dependent on one’s ability to “be the interpreter”. Anything short of this standard will result in defective code or code that produces unexpected results.
Which raises the question, where then is the definitive coding manual or comprehensive course of instruction that enables one to accomplish this in javascript?
Outtanames999 on May 31st, 2010 at 5:31 pm
[...] discussed the similar clause before, at least the 3rd edition one, when answering Baranovskiy’s JavaScript quiz. I thought I had understood that arguments was always bound to the named arguments of the function. [...]
Mysterious arguments object assignments | NCZOnline on November 2nd, 2010 at 9:01 am
Regarding Example #2, you wrote:
Named function expressions are not considered function declarations and therefore don’t get overridden by variable declarations.
I comprehended what you mean, but I think here it’s better to be variable initialization, because by literal meaning, even function expressions are considered as function declarations, it still cannot be overridden by variable declarations( as you commented, variable declarations are always be overridden by function declarations)
Marvin on December 21st, 2010 at 9:09 am
Comments are automatically closed after 14 days.