Day 15 100 Days of Code

Last night I spent a lovely hour with my first love (programming languages), JavaScript.

I’ve been sitting in some interviews at work. We’re asking candidates JavaScript questions that I’m not sure I could answer. So I spent an hour last night poking around JavaScript closures reminding myself why this following snippet does what it does:

(function doThese(){
  for (x = 0; x < 5; x++){
    console.log('x in for', x);
    setTimeout(function(){
      console.log('x here',x);
    },0);
  }

  console.log('foo', foo);
  console.log('bar', bar);
  
  function foo(){
    return 'foo';
  }
  
  var bar = function (){
    return 'bar';
  }
})()

The for…loop at the top is the focus of my attention. As written this will console log the number 5 five times. What would I change here to make it console.log 0, 1, 2, 3, 4 instead?

Instead of simply calling the function in setTimeout, use this to wrap a return of function like this:

(function doThis(){
  for (var i = 1; i <= 5; i++) {
      setTimeout(function(x){ return function(){ console.log('x inner', x) } }(i), 0);
  }
})()

If this #100DaysOfCode is news to you, here’s day #1 with more information: http://stephanietech.net/2017/01/06/100daysofcode/ https://github.com/SFoskitt/100-days-of-code/blob/master/log.md

Published: January 26 2017