Live data from Hacker News

JavaScript Interview Question

cam.ly

31–40 of 63 posts

Re: JavaScript Interview Question

#31
post #21

Earlier quoted context omitted.

It won't alert quite what you want - when you click on each element in the list, it will alert "4". 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 appl…

The function in the click handler does take a parameter 'e' (...or whatever you call it) which is an Event object. But I think you're on to something by using currying.

Well yes, the function is called with a MouseEvent as one of the arguments, so you could use the "arguments" object to access it.

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 

Re: JavaScript Interview Question

#32
post #13

I think they all alert '3' because of the missing 'var' keyword.

Just adding var wouldn't be enough, you're still referencing the variable from the outer scope. You need to create your own copy. Instead of: 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 :)

That won't work either. You're still setting the variable to the global variable i. The only way I can think of doing this is as follows

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

Re: JavaScript Interview Question

#33
post #28
post #4

Earlier quoted context omitted.

Please do.

this is what I usually tell people to do: var els = document.getElementsByTagName('li');//use var unless you really really really meant global for(var i=0; i

i agree with the choice of code, but I have a different style for laying out the code.

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

Re: JavaScript Interview Question

#34
It's not the question itself with which I have a problem; it's the whole approach. Let me explain...

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 , it causes , the compiler does , the operating system does , which results in ." To which I think, "Great. Who cares. I would have just done 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.

Re: JavaScript Interview Question

#35

Spoiler Alert! 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…

"The value of i is figured out only when the link is clicked." 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.

ahh thank you this makes more sense. If I understand you correctly...

- 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-link item executes alert(i) with i = 4, when clicked.

Re: JavaScript Interview Question

#36
post #34

It's not the question itself with which I have a problem; it's the whole approach. Let me explain... 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 , it causes , the compiler does , the operating system does , which results in ." To which I think, "Great. Who cares. I would have just done and been done…

I don't completely disagree with you; but I do have some comments (numbered per your items):

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.

Re: JavaScript Interview Question

#37
post #26

is it silly of me to think that this doesn't seem hard enough to be an interview question? i'd be more interested in whether (and how quickly) someone could grasp a complex problem

It could have been the first question of a series. This would probably make a pretty good screen question, at least.

Re: JavaScript Interview Question

#38
post #3

A while back a couple of colleagues sat down and came up with our own set of JS interview questions. Here's what we came up with: 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.

They seem like good questions. As an addendum to the final question in second link, it might also be worthwhile checking the interviewee's understanding of "this" in other contexts too.

Re: JavaScript Interview Question

#39
post #3

A while back a couple of colleagues sat down and came up with our own set of JS interview questions. Here's what we came up with: 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.

What its the percentage of developers that pass the questions?

I don't think many entry level programmers will think about returning a function to implement say, but I can be wrong.

Re: JavaScript Interview Question

#40
post #26

is it silly of me to think that this doesn't seem hard enough to be an interview question? i'd be more interested in whether (and how quickly) someone could grasp a complex problem

When hiring front-end developers, there's a lot of people out there who fall into the "web designer guy who learned some coding along the way." They aren't engineers--and while they likely could study and learn, they really haven't. To me this is a really simple screening question; an engineer who understands closures, scope, and variable references will immediately say, "yeah, I see what's happening here..." and answer correctly.

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.

Post reply on HN