Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to insert an element into an array at a position

Short answer

splice(index, 0, item) inserts an element at the index without removing anything:

const letters = ['a', 'b', 'd'];
letters.splice(2, 0, 'c');
 
console.log(letters.join(', '));

Output:

a, b, c, d

To the beginning

unshift() adds elements to the start of the array:

const queue = ['second', 'third'];
queue.unshift('first');
 
console.log(queue.join(', '));

Output:

first, second, third

Without changing the original

toSpliced() works like splice(), but returns a new array:

const letters = ['a', 'b', 'd'];
const full = letters.toSpliced(2, 0, 'c');
 
console.log(letters.join(''), full.join(''));

Output:

abd abcd

Common mistake

splice() returns the removed elements, not the new array. With zero removed elements the result is empty:

const letters = ['a', 'b', 'd'];
const result = letters.splice(2, 0, 'c');
 
console.log(result.length);

Output:

0

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.