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?
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”.
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 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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With