How to add array element at specific index in JavaScript?

javascript array arrays

To insert element into JavaScript array, splice method should be used. For inserting first parameter should be index before which new element will be inserted.  Indexes are counted from zero. Second parameter should be 0 as we do not remove element. The splice method must be called on array itself and it will modify this array.

Example of inserting at beginning

Use index value of zero to insert at beginning.

var x = [111, 222, 333];
x.splice(0, 0, 666);
// Array is now [666, 111, 222, 333]

Inserting at arbitrary index

Passing as parameter on integer value greater than zero, results in adding element before that index value.

var x = [111, 222, 333];
x.splice(2, 0, 666);
// Array is now [111, 222, 666, 333]

Out of range index

If we set index parameter to be greater than maximum existing array index or negative value, the new element will be appended to end of array. However good practice is to avoid such constructs, instead use array.length or better push method.

Adding element to end of array

The easiest way is to use push method.

var x = [111, 222, 333];
x.push(666);
// [111, 222, 333, 666]