Register your Account

Sign Up with us and enjoy!

A password will be e-mailed to you.

JavaScript Interview Question

Posted January 20, 2011 in

We recently came across a good JavaScript interview question. We won’t disclose the name of the company using it, but we hope that this helps interviewees test their knowledge, and employers looking for good ways to design questions:

  1. Look at the following code. What does it do? What happens if you click on the li elements?
  2. Establish what happens when you click on the li elements. Can you guess? Ask the interviewee to explain why this happens.
  3. Ask how the code can be fixed so that clicking on each element outputs an alert corresponding to its order in the list (the desired behavior)

This simple exercise covers a lot of bases in evaluating someone’s JavaScript understanding in a short period of time. What do people think? What are good followup questions?

<html>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
</ul>
</body>

<script type="text/javascript">
  els = document.getElementsByTagName('li');
  for(i=0; i < els.length; i++){
    els[i].addEventListener('click', function(){alert(i);}, false);
  }
</script>
</html>




Discussion

6 Comments
  1. Is it a good question? It is a rather simple question, so it depends on who you are trying to hire. A lead JS engineer? No. A junior webdev? Sure.

    A similar, and good follow-up question (one that I ask all the time) is… instead of a list, I present them with:

    <a>
    <b>
    <c>
    <d>

    Next I ask them to add event listeners to alert() the content of each <div> when clicked. Often they do code that looks the same as the code in the example. Then, I explain why adding an event listener to every single element can be expensive, so what’s a better way to do it?

    Answer: Add a wrapper around the 4 divs, and add one event listener to that. This follow-up could be adapted to your question by saying they only get 1 event listener to bind, and look for them to attach it to the <ul> instead.

    This will test the candidate’s knowledge of “event bubbling”, essential knowledge for anyone creating real JS web apps.

  2. Strange how the script is located outside of the body tag. What are the implications from this?

  3. Heh, we use that same question for our tech interview. I knew what it was about before I finished reading, just from glancing at the code :)

    Definitely agree it’s a good question: it’s short, it requires a reasonable understanding of the language, and it asks the candidate to solve one of the most common newbie js mistakes.

  4. It’s cute, but that is one of the concepts covered in Javascript: The Good Parts by Douglas Crockford. So if they have read that, this will be too easy.

Trackbacks

  1. TERRENCE

Leave a Response

If you have a question or comment, or just need to get in touch, please use the form below.