#How this works..?
12 messages · Page 1 of 1 (latest)
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
Thanks for reply @crimson arrow , i am aware of your method...i saw this example in some website and now I'm curious like WHAT THE HELL it's working mechanism 😆
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
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
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..,.
That's literally WT.F moment when I saw that, thanks @cunning thicket for clarifying