Home > Enterprise >  How does this for loop array works?
How does this for loop array works?

Time:10-08

I just learn about array today but I don't actually understand this code I'm learning.

let units = [1, 10, 100, 1000, 20];

for(let i = 0; i < units.length; i  = 1){
    console.log(units[i]);
}

How would console.log(units[i]); return 1, 10, 100, 1000, 20 and not 5?

Could you guys explain to me the way I will actually understand this?

CodePudding user response:

units is an array.

units[0] gets you the first item in the array (1). units[1] gets you the next item in the array (10). and so on.

So as i is incremented with each loop iteration, you get the corresponding item from the list.

CodePudding user response:

Just for your information.

This below is the initialization of list of numbers in a variable units

let units = [1, 10, 100, 1000, 20];

Now the loop begin.

for() is the loop.

Where 1st params let i=0 tell the starting point of the array.

2nd params i<units.length defined the length of array where the loop needs to be end

3rs params tell the index need to be increment each time the loop executed. For eg: when index i is 0, then value units[i] = 1. After its execution the value of index i is incremented by 1 due to i as third param of for() loop.

The loop will continue until it meets the value of last index defined in second params that is i<units.length

for(let i = 0; i < units.length; i  = 1){
    console.log(units[i]);
}

I hope it made you clear.

  • Related