For Looping Thru Array in JS

Hello, I am so sorry for always asking silly questions but except these forums I have no other option to get any other personal help.

OK I have this code. What I am doing is finding out and printing how many items are there in the array. And the output is 6 items… But there are are only 5 items… Then why showing 6. I know that array start counting from 0 based index. So 6 is in position 4.

var Arr = [2, 3, 4, 5, 6];

var total=0;
for (var i=0; i < Arr.length; i++)
{
total = Arr[i];
}

Help please.
Thank you.

With the current code, you are assigning the value from the array to the total variable. So if the 6 at the end of the array was instead 42, the total would end up being 42.

Instead, you want to increase the total by 1 each time through the loop, or without the loop just get Arr.length

always glad to help.
but lest start with the correct way to find the size (number of items) in an array… theArrayVar.length. Thats it! Anything else is overcomplicating it and will lead to errors. What you are currently doing loops through the whole array to return what is actually a property of the array object itself.

also, setting total = Arr[i] doesn’t count the array, it simply gives you, at the end of the loop, the value at the last position of the the array;

if you MUST do this this way, replace that line of code with total = i; and you will get the answer you expect. BETTER YET, you could just get rid of total, since at the end of the loop i will equal Arr.length (5).

hope that clears things up

Ohhh yes… arr[i] means position of each item in a array… Am I correct ?

My new code is this:

var Arr = [2, 3, 4, 6, 8, 10];

var total=0;
for (var i=0; i < Arr.length; i++)
{
total = Arr.length;
}

it means the item at position [i] in the array, but basically yes.

and your new code will yield the right answer… but really you are setting the value of total , over and over( you are setting it Arr.length times to be exact), there is no reason for that.

all you need is:
var Arr = [2, 3, 4, 6, 8, 10];
total= Arr.length;

2 Likes

Note that the length property gives the relative position of the last element in the array and not a count of the number of elements in the array (unless all the positions in the array actually exist).

See https://www.sitepoint.com/quick-tip-create-manipulate-arrays-in-javascript/ for an in-depth explanation of how the length property works.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.