Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the JS array length property ever return a negative value?

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?
}
like image 229
Uncle Slug Avatar asked Sep 03 '15 22:09

Uncle Slug


People also ask

Can JavaScript array length be negative?

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.

Can an array have a negative length?

Array dimensions cannot have a negative size.

What does the length property of an array return?

The length property sets or returns the number of elements in an array.

Can an array length be less than 0?

No, the length of an array is a non-negative integer.


2 Answers

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 a length property whose value is always a nonnegative integer less than 232.

Update: Answer still holds for ES2020

like image 171
josh3736 Avatar answered Sep 20 '22 03:09

josh3736


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);
like image 31
potatopeelings Avatar answered Sep 20 '22 03:09

potatopeelings