Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this abstract repetition works?

I'm reading some Javascript stuff since i dream about being a good JS developer. I kind of know how to use the basics to fullfill my PHP needs, but there are still some doubts.

I saw some some examples and got this:

function repeat(n, action) {
   for (let i = 0; i < n; i++) {
      action(i);
   }
}

let labels = [];

repeat(5, i => {
   labels.push(`Unit ${i + 1}`);
});

console.log(labels);

So, i can use it to repeat some basic function if needed. Understood, but in another case, i could use the same function with some different approach.

Why does the variable i becomes a counter/iterator if I suppose to pass a function?

I've used it before all time, but still don't know how does it works, so i can't use it when trully needed.

like image 805
Victor Augusto Avatar asked Jan 25 '26 03:01

Victor Augusto


2 Answers

i isn't becoming an iterator. In the code, you are using es6 shorthand notation for describing a function. i is the lone argument to the function.

i => {
   labels.push(`Unit ${i + 1}`);
});

is the same as

function(i){
  labels.push(`Unit ${i + 1}`);
} 

Please see more in this reference on shorthand notation

Edit: To answer your comment "What is adding it", you must look at the repeat(n, action) function more closely. It also may be confusing to you that i is used in both cases so I will rewrite the function to help you understand. This function uses a for loop to iterate from 0 to n

for (let idx = 0; idx < n; idx++) {
   action(idx);
}

and invokes the action with the current for loop index idx. So for you example:

Iteration 0: action(0) -> labels.push(`Unit ${0 + 1}`);
Iteration 1: action(1) -> labels.push(`Unit ${1 + 1}`);
Iteration 2: action(2) -> labels.push(`Unit ${2 + 1}`);
Iteration 3: action(3) -> labels.push(`Unit ${3 + 1}`);
Iteration 4: action(4) -> labels.push(`Unit ${4 + 1}`);

Please do note that the repeat's declaration of i is local to its function body, just as the i in i => { labels.push(Unit ${i + 1}); } is local to its function body. These two i values are not referencing the same value in memory and can be renamed as I did in my explanation

like image 114
mistahenry Avatar answered Jan 27 '26 18:01

mistahenry


In repeat function you are passing forloop index to callback

function repeat(n, action) {
   for (let i = 0; i < n; i++) {
      action(i); // here you are passing index to callback
   }
}

and you are getting index as params

repeat(5, i => { // Here you will get params that is passed by repeat function
   labels.push(`Unit ${i + 1}`);
});

Hope this will help

like image 30
Jay Avatar answered Jan 27 '26 19:01

Jay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!