JavaScript Closure incorrect behavior

Viewed 78

Here is a small snippet of code where I feel the closure function has a weird behavior ...

var arr = [5, 6, 7, 8, 9, 0];
var someFn;

arr.forEach(function(val, idx) {
  if (!someFn) {
    someFn = function() {
      console.log(`B: ${idx} : ${val}`);
    };
  }
  console.log(`A: ${idx} : ${val}`);
  someFn();
});

The final console output is ...

A: 0 : 5
B: 0 : 5
A: 1 : 6
B: 0 : 5
A: 2 : 7
B: 0 : 5
A: 3 : 8
B: 0 : 5
A: 4 : 9
B: 0 : 5
A: 5 : 0
B: 0 : 5

I expect someFn to process the incremental value when the forEach is processing, but it always outputs the first value which is "idx: 0, val: 5".

I dont think this is the right behavior because someFn is creating a closure which encloses the variables idx and val and both those variables are changing in the outer function.

Appreciate if someone can kindly explain this behavior.

2 Answers
Related