#How this works..?

12 messages · Page 1 of 1 (latest)

azure thorn
#

`var arr = [];

for (var i = 0; i < 3; i++) {
arr.push(
((ii) => () => console.log(ii))(i));
}

arr.forEach(f => f());`

(output: 0,1,2)

crimson arrow
#

Are you trying to achieve the output of [0,1,2]? Will be tweaking this as:

var arr = []

for (var i = 0; i < 3; i++) {
arr.push(i)
}

console.log(arr)
It outputs [0,1,2]

You initialize the the var arr as empty array

The Loop means,
starting with zero - save in i
ends with less than 3 (which is 2).
Increment i by 1 every time it run.

The inside of the loop is pushing the value of i to the array. So the value of arr in every run is

First = [0]
Second = [0,1]
Third = [0,1,2]
Loop ended

azure thorn
cunning thicket
#

Wow, where did you get that chunk of code from vicky? That's an incredible convoluted and in my opinion totally unmaintainable and overly complex piece of code... basically you can break it all down to this:

After the for loop the array contains 3 functions... then the code is invoking each one of those functions - and all the functions do is log out the index in the array...

#

Here I've broken it down and reformatted a little and also changed the variables so it's less confusing:

var arr = [];

for (var i = 0; i < 3; i++) {
  arr.push(
    ((j) => {
      return () => console.log(j); // returns a function
    })(i) // an IIFE which calls the above function passing i as it's parameter - therefore console.log(i) essentially
  );
}

arr.forEach((f) => f()); // this calls each of the inner functions
azure thorn
#

var arr = [];

for (var i = 0; i < 3; i++) {
arr.push(
((j) => () => console.log(j))(i)
);
}

So array here has,

[
() => console.log(0),
() => console.log(1),
() => console.log(2)
]

#

So, (ii) is just acts like placeholder...

I thought of why it is taking (00)..haha

#

That code is from....i will search in history tab, probably from geek for geek

cunning thicket
#

yep, you're correct the array contains those functions and yeah, the ii notation is incredibly misleading since i is already defined but yes, it's just another function variable which is why I renamed it to j for clarity..,.

azure thorn