A Common JavaScript Interview Question Asked By Google & Amazon

I have seen this question asked by Google, Amazon and even smaller tech companies to weed out JS developers.

Adi S
Adi S
Nov 27 · 3 min read

It is a popular and typical closure question:

This code deals with closure, setTimeout and scoping

Interviewers are asking this type of question to really test your knowledge of important JavaScript concepts. By answering this question correctly, you can display your understanding of block scope, closures, anon functions, and Immediately Invoked Function Expressions (IIFE).

So what does the code above output after the 3 seconds are up?

Confused? Keep reading below

The reason we are seeing this output is because the setTimeout function creates a function() (which is the closure). Rememeber: a JavaScript closure is when an inner function has access to its outer enclosing function’s variables and properties. The function it creates has access to the outer scope which contains the for loop with the index i. Now after the 3 seconds go by (3000) the function can then be executed and it starts console logging the value of i. What is the value of i here? At the end of the loop, i is 4 because it goes through 0, 1, 2, 3, 4. So, when it gets to 4 the loop stops. You can also see this because arr[4] does not exist (undefined).

Since the original code has const, let’s look at an ES6 solution/fix which is simple:

Replace var with let

With you ES6 you can create a solution to the code quickly. By changing var to let, it allows the value of i to be “held” until after the setTimeout is finished.

And then we get what we wanted:

The correct output for each index in the array

For those not as familiar with ES6, here is an older JS way to solve it:

Produces the same output as the ES6 code above

If this example was confusing, I would suggest by reading up on JS closures and scoping. A good place to start would be my last Medium post on Javascript scoping 😉!

JavaScript in Plain English

Learn the web's most important programming language.

Adi S

Written by

Adi S

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade