Would there ever be an instance when the JavaScript array length property returns a negative value? I'm assuming the answer is no, but I was wondering if there would ever be a need to account for negative values when comparing the length of an array in an if statement, for example.
var x = y.length;
if (x === 0) {
return false;
} else if (x > 0) {
return true;
} else alert("error"); // is this necessary?
}
No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.
Array dimensions cannot have a negative size.
The length property sets or returns the number of elements in an array.
No, the length of an array is a non-negative integer.
No.
The spec for the length
property says:
The
length
property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.
There cannot be -1 properties.
Also, and more explicitly, the spec for Array
says:
Every
Array
object has alength
property whose value is always a nonnegative integer less than 232.
Update: Answer still holds for ES2020
Not normally (as other answers have pointed out), but an object that is an instance of an array can have a negative property called length
var b = Object.create([]);
b.length = -1;
alert(b instanceof Array)
alert(b.length);
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