Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "array.length -1" mean in JavaScript?

I know how to use the JavaScript for loops to cycle through arrays for example, but I still didn't understand what the array.length -1 means, specifically the -1 part.

When using a for loop over an array we have something like this:

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

But I've seen also something like this, sometimes:

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

In the second case, why there is the "-1" in the array.length and what does it do? Also why sometimes there is and sometimes isn't it shown?

like image 580
Adrian Ghinea Avatar asked Jan 26 '16 21:01

Adrian Ghinea


People also ask

What is array length 1 in JavaScript?

The JavaScript array length property is given in a one-based context. So, a JavaScript array with one element will have a “length” of “1”. If a JavaScript array has four elements, then that array's “length” property will have a value of “four”.

Does array length start 0 or 1?

Arrays in Java use zero-based counting. This means that the first element in an array is at index zero. However, the Java array length does not start counting at zero.

What is array length in JavaScript?

What exactly is the JavaScript Array length property. By definition, the length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. The value of the length is 232. It means that an array can hold up to 4294967296 (232) elements.

Does array [- 1 work in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).


Video Answer


1 Answers

If your array has 4 elements, for example

var elementOfArray = [7, 9, 0, 2]

and you want to reach those elements. In that case, you need to know that elementOfArray[i] represents element of your array and i is the index.

For that reason, if you add '-1' on your array length; you can see whole elements in your array like elementOfArray[0]---7, elementOfArray[1]---9, elementOfArray[2]---0, elementOfArray[3]---2. See! you took the whole number in the element.

If you do not subtract 1 of array length, you would take an error. Because there is no elementOfArray[4] that represents any element of your array.

like image 82
Dilan Avatar answered Oct 04 '22 16:10

Dilan