JavaScript Interview Question
cam.ly
cam.ly
I have absolutely no faith that someone in an interview who doesn't figure out the scoping issue in the interview doesn't understand Javascript scopes. In the "real world" of a job, the problem is presented like this: "This code exhibits the following behaviour: It outputs a four every time instead of one, two, three, and four Find out why and fix it, please."
Given as a gotcha, I would stare at the code, and possibly figure out the scope issue. Then I would keep staring. Is this the only "gotcha," or has the interviewer diabolically inserted two bugs and I have to find the second one?
The entire process would make me feel like I was in an adversarial position, where the interviewer is trying to point his finger at me and yell "FAIL! I pwn3d you with my l33t Javascript questioning skillz!!"
FWIW, I think I understand the solution. In fact, I wrote a blog post about the exact same thing:
https://github.com/raganwald/homoiconic/blob/master/2010/10/...
But nevertheless, I know that from time to time I unwittingly make this mistake when coding and quickly fix it. I don't have a lot of confidence I would be guaranteed to get the correct answer in an interview every time.
Which is maybe why I don't like it as an interview question: Perhaps I'm not smart enough to get the answer right every time. Perhaps the only questions I like are the ones I like to be asked :-)
each list item alerts 4 when clicked. This has to do with closures in js. The way I understood it (and please correct if inaccurate) is that each list item has an event listener that calls function: alert(i). However, it's not true that each list item has its own value for i. The value of i is figured out only when the link is clicked.
Once script finishes, i has the value 4, and when clicked on, each list item draws from this value of i instead of the one in which it is originally assigned.
This makes it sound a bit like magic. A more accurate description is that the usage of the variable "i" within the closure is simply a reference to i in the outer function--not a copy of the value.
A great follow-up is to describe the memory implications of what they've done here and how memory use can be improved.
- each list item has a pointer to a function: alert(i) (functions are first class objects)
- the value of i is determined from the outer function (which is in some unraveled way the for(i=0; i<els.length; i++)) because it is within the scope of the above function
-link item executes alert(i) with i = 4, when clicked.
Can the interviewee code: https://gist.github.com/633341
Can the interviewee read/debug code: https://gist.github.com/633087
I used these questions during a couple of interviews. They seemed to work well.
I don't think many entry level programmers will think about returning a function to implement say, but I can be wrong.
function say(arg) {
return function(word) {
alert(arg + " " + word);
};
}
It solves "hello world", but wouldn't work for something like say("dogs")("and")("cats"). Are you expecting an arbitrary number of function returns? function say(x)
{
return function (y) { alert( capitalize(x) + " " + capitalize(y)); }
}
Where capitalize makes the first character uppercase.Thanks for the heads up.
I would be blown a way if someone came up with solution that could handle arbitrary function returns. My friend actually wrote an interesting article on the subject. Here's the link if you're interested: http://msdn.microsoft.com/en-US/scriptjunkie/gg575560.aspx
var say = (function() {
var savedArgs = [];
return (function recurse () {
if (arguments.length) {
for (var i=0, arg; arg=arguments[i]; i++) {
savedArgs.push(arg);
}
return recurse;
} else {
alert(savedArgs.join(' '));
savedArgs = [];
}
});
})();// e.g. say('Hello')('World')('!!')();
// --> alerts "Hello World !!"
I'm not a JS expert by any means, so if I'm doing something stupid in this code, I'd love to know.
var say = function(word) {
words = [word];
func = function(word2) {
if (word2) {
words.push(word2);
return func;
}
else {
print(words.join(' '));
}
}
return func;
};
say('hello')('bob')('how you doing?')();*note I have the function 'print' aliased to console.log for convenience.
Having conducted likely close to a hundred UI Engineer interviews, definitely over a hundred phone screens, and seen what feels like thousands of resumes (probably hyperbole on that last one), I can assure you that many candidates I've seen couldn't answer this question.
1. Every programmer I have ever worked with (except for an inept few) knew something that I didn't. They could show me a piece of their code and say, "When you do <a>, it causes <b>, the compiler does <c>, the operating system does <d>, which results in <e>." To which I think, "Great. Who cares. I would have just done <x> and been done with it."
2. Looking at someone else's code and asking what it does is great: if you have to maintain that code. Otherwise, who cares? If I want to build something, I build it with what I know. What I know may or may not include the best tool in the tool box, but again, who cares? Something built 90% optimally today always defeats something built 100% optimally tomorrow.
3. Describing what some preexisting code does is a good academic exercise, but that's all it is. In my experience, I have observed zero correlation between programmers who would have done well on this question and those who could build and deploy great stuff quickly.
4. For some things, it's absolutely critical to know what goes on under the hood. For others, it's a waste of time. Something than improves performance 1000x or improves up time to five nines is the former. Something that's slick is probably (but not always) the latter. I think this question is probably the latter.
If I have 15 to 30 minutes with someone and want to find out how well they'll be able to build something, I'll have them build something and ask questions about what they just wrote. I have always learned more about them this way than by looking at 3rd party code.
2. In a lot of jobs, the ability to read, maintain, update, and extend existing code is considered far more valuable than "building it yourself in your own way." While it's true that there's "more than one way to skin a cat," I'd rather be consistent within a single codebase about how we're skinning that cat. If you can't read and understand code that came before you, you're going to limit your career options to doing nothing but one-off client work.
3. Depends on what you believe "very quickly" means; I would argue that someone who can read and extend preexisting code can work faster than an engineer who wants to build everything him-or-herself.
4. This question isn't a case of performance optimization (though it certainly can be seen that way if you want to talk about the memory and cpu implications of creating tons of functions). This question exposes whether a candidate has an understanding of some pretty fundamental concepts of using closures within javascript and how they impact scoping.
I totally agree that you also want to get a candidate to build something; but this question is very useful at exposing their understanding of how javascript truly works.
If you're planning on being an author, it's useful to first be able to read, and to read loads. That's how you learn.
The interview question is a simple rookie js question that basically asks "Do you know javascript to any degree".
It also has the side benefit of letting candidates see our codebase, bug tracking, etc.
As far as asking how technologies work under the hood. I really don't care if a web developer knows how pointers work, etc. If they can consistently get challenging problems done, that's all I need to know.
els[i].addEventListener("click",(new function(){var this._i = i; function message(){alert(_i);}}).message);
it works fine and it's much shorter and easier to read than nested function declarations
I'm guessing one would have to create an object with a scope that holds the right value, on each turn through the loop.
els[i].addEventListener('click', function(){alert(i);});
Do: els[i].addEventListener('click',
function() {
var j = i;
alert(j);
});
Edit: This is wrong, archgoon has the correct answer below. That'll teach me for jumping on closure problems in the morning :)Edit: Oops, this is wrong as well. :-)
You could make the function take a parameter, then return a function which uses that parameter, or use currying.
Edit: I've posted a working version in my comment further down, http://news.ycombinator.com/item?id=2124559
els[i].addEventListener('click',function(k){function(){alert(k)}}(i));
EDIT: See lhorie's suggestion below for a much cleaner way of doing this. http://news.ycombinator.com/item?id=2124532
Here is a fix http://jsfiddle.net/hBe3c/
This is because the function assigned to the click event of each li is bound to the "i" variable used in the loop by a closure. Variable i is incremented to 4 before the loop ends, so that is what each will print.
You could use make the function used in the click handler take a parameter, then use partial function application (or currying) to fix the value of the parameter.
What I was thinking of, was something along the lines of:
// From http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.curry = function() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments)));
};
};
els = document.getElementsByTagName('li');
for(i=0; i < els.length; i++){
els[i].addEventListener('click', function(x){
alert(x);
}.curry(i), false);
} var els = document.getElementsByTagName('li');//use var unless you really really really meant global
for(var i=0; i < els.length; i++){
(function(i) {//creates new scope for each iteration
els[i].addEventListener('click', function(){alert(i);}, false);
})(i);
}i dislike the declaration and immediate execution of an anonymous function. i much prefer to give it a name, move it out of the loop itself and then call it within the loop. it makes reading the code more top-to-bottom.
with this approach, when I get to the anon func declaration, i have to scan down looking for when it is invoked. while indentation helps, i then have to backtrack up to the beginning of the func declaration.. and hopefully i haven't lost track of what the execution context for the anon func is and so forth...
But yeah, if we're gonna be super nitpicky, yeah sure, improve the for loop also, while we're at it.
for (var i = -1; els[++i];) {//given the code in the loop body, this is shorter and faster for (var i = -1; els[++i];) ?
Otherwise, the alert won't trigger on the first li element. var els = document.getElementsByTagName('li');
for(i=0; i < els.length; i++){
var j = i;
els[j].addEventListener('click', function(){alert(j);}, false);
}Your confusion is because of a javascript quirk
for (...) {
var foo = bar
}
is actually the same as var foo
for (...) {
foo = bar
}
Notice how you only ever have one fooWhat you need is:
for (...) {
(function(bar) {
var foo = bar
})(bar)
}
which create a new foo every time you loop