DEV Community

Cover image for 3 topics in 1 JavaScript interview question

3 topics in 1 JavaScript interview question

Maciek Chmura on March 12, 2019

Programming interviews are hard. Live coding during the interview is even harder. I have a feeling that as soon as I have to type code in front of ...
Collapse
 
laurieontech profile image
Laurie

Really well written! One minor thing, based on that loop, I believe it will log 0, 1, 2 and not 1, 2, 3? That detail doesn't effect all the wonderfully explained concepts though!

Collapse
 
maciekchmura profile image
Maciek Chmura

ups :) you are absolutely right, thank you for pointing this out :)

fixed

Collapse
 
benjaminadk profile image
benjaminadk

I believe before the addition of let one way to solve this would be to wrap the call to setTimeout in an IIFE. I guess by immediately invoking the outer function with the current value of i it seals the value at that moment vs getting it from the global scope when the inner function is called.

  for (var i = 0; i < 3; i++) {
    (function(i) {
      setTimeout(function() {
        console.log(i)
      }, 1000)
    })(i)
  }

// 0 1 2

Collapse
 
josef profile image
Josef Aidt

Maciek this is great! The final recap really tied it together, and now I understand the logic behind this question much more thoroughly. Excellent stuff, can't wait for the next one.

Collapse
 
maciekchmura profile image
Maciek Chmura

I'm blushing, thank you ;)

Collapse
 
slatham profile image
Steve Latham

The backpack analogy is a good one. I often think the names given to these concepts make them harder to learn. Closures to me would indicate some kind of ending or return. I assume it is something to do with being enclosed, maybe? Similarly the "rest parameter" sounds like it's going to have a little pause before entering your function. I had a less imaginative way to remember closures - savedScopeForLater! From now on though, Closure = backpack!

Great article, Maciek!

Collapse
 
joeberetta profile image
Joe Beretta

Thank you very much. In a days I will be interviewed and it's very helpful!!! 👌👌👌

Collapse
 
maciekchmura profile image
Maciek Chmura

Good luck on the interview, I hope you will get the job :D

Collapse
 
joeberetta profile image
Joe Beretta

Thanx) And I hope😊

Collapse
 
4rontender profile image
Rinat Valiullov • Edited

Yet a little another solution

for(var i = 0; i < 3; ++i) {
    setTimeout((function(z) {
        console.log(z)
    }).bind(null, i), 1000)
}

// 0
// 1
// 2
Collapse
 
carlfoster profile image
Carl

Will this guarantee that it emits 0,1,2? Since setTimeout() is async, I don't think it guarantees execution order.

Collapse
 
vekzdran profile image
Vedran Mandić

This is pure essentials in JS. Good wrap up! Thanks for writing and sharing.