Home > front end >  What does "array.length 1" mean in JavaScript
What does "array.length 1" mean in JavaScript

Time:06-12

I know how to use Javascript for loops to cycle through arrays. But I still don't fully understand what the array.length 1 is doing, specifically the 1 part.

When using a for loop I know it goes like this

for(let i = 0; i < array.length; i  ){...}

But I'm also seeing this

for(let i = 0; i < array.length   1; i  ){...}

I previously thought that array.length 1 was the same thing as letting i = 1 but my code hasn't worked when doing that, for instance

for(let i = 1; i < array.length; i  )

is not the same thing as the for loop above. Can someone explain why?

CodePudding user response:

This

for(let i = 0; i < array.length; i  ){...}

loops from indicies 0 to array.length - 1. For example, with an array with 3 items, this iterates over is of 0, 1, and 2.

This

for(let i = 0; i < array.length   1; i  ){...}

is strange. It loops from indicies 0 to array.length. For example, with an array with 3 items, this iterates over is of 0, 1, 2, and 3. This means that if something inside the loop references array[i], that value will be undefined on the final iteration.

Most of the time, seeing something like that would make me think someone made a typo or logic error - though I wouldn't be surprised to see a few algorithms that used something like it.

This

for(let i = 1; i < array.length; i  )

iterates from indicies 1 to array.length - 1. For example, with an array with 3 items, this iterates over is of 1, and 2.

There will be one less iteration than elements in the array. This means that, if the loop body always references array[i], and not array[i - 1], then the first element in the array will always be skipped over.

This is much less common than starting at 0, but could be seen, especially when the logic requires comparing certain adjacent elements against each other (for example, array[0] to array[1], and array[1] to array[2], and so on).

CodePudding user response:

Array.length   1

simply put is just the number of elements in the array and add 1.

An array with n elements has a length of n , so your loop will run n - i times when using array.length. If let i =0 , then your loop will run n times. If i = 1 , then your loop will run n-1 times if using array.length. So you will be missing 1 iteration of your loop.

If you need to use i=1 to start your iterations, you should use array.length 1 to get the equivalent number of iterations.

for(let i =0;i<array.length;i  ){} // n iterations

is the same number of iterations as

for(let i= 1;i<array.length  1;i  ){}  // n iterations
for(let i=1;i<array.length;i  ){}  // n-1 iterations 

will always be 1 less iteration.

And remember, Array indexing uses a 0-based counter, so array[0] is the first element of every array.

  • Related