Dixie Flatline
Dixie Flatline

Reputation: 75

Why JS allows negative indices in array?

Why negative indexing of an array in JS doesn't raise an error? It looks like it not intended to have elements with a negative index in an array:

UPD. The question is not "why it is thechnically possible" buth rather "why it is allowed by design".

[RESOLVED] Short answer: there is no particular reason, it just happened to become like this.

Upvotes: 4

Views: 5574

Answers (3)

termosa
termosa

Reputation: 701

Arrays are the special type of object in JavaScript. It has an extra list of methods and properties (like .length and .forEach), and also it has a list of used indexes (integer positive number starting from zero higher). But just like any other object, it can have additional properties:

var arr = ['A', 'B'];
arr.extra = 'C';
console.log(arr[0], arr[1], arr.extra); // A B C

Because of object properties can be accessed not only via dot but also via square brackets you can access any property using array-like syntax:

var obj = { extra: 'D' };
console.log(obj['extra']); // D
console.log(arr['extra']); // C

Using the same syntax you can assign properties:

obj['x'] = 'E';
obj[33] = 'F';
arr['y'] = 'G';
arr[-1] = 'H';
console.log(obj.x, obj[33], arr.y, arr[-1]); // E F G H

You can safely use numbers as a property name for the object, it will automatically be converted to a string.

The only difference is when you use positive integer values for the name of the property. Those are interpreted as array indexes.

var arr = [];
arr[0] = 'A';
arr[1] = 'B';
arr[-1] = 'C';
arr.forEach(value => console.log(value)) // A, B
console.log(arr.length); // 2
console.log( Object.keys(arr) ); // ["0", "1", "-1"]

Upvotes: 6

Nikos M.
Nikos M.

Reputation: 8355

Arrays in javascript also can work as hash objects (as almost all objects in js including functions). So doing: a[-1] = -1 simply defines a new key in the array (as object hash) with key value "-1" and value -1.

You should know that almost all objects in javascript can be used as hash objects as well. This is what you see. However these keys (which are not positive integers) for arrays do not count as array keys in the normal sense, only as hash keys.

Upvotes: 1

Zachary Haber
Zachary Haber

Reputation: 11047

JS allows negative indices in an array for the simple reason that they are objects under the hood. You can also put [].blah = 5 and it would be valid but a terrible idea.

Upvotes: 0

Related Questions