Replace the first Element of an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

Replace the first Element of an Array #

To replace the first element of an array, use bracket notation [] to access the array element at index 0 and change its value with the replacement, e.g. arr[0] = 'replacement'.

index.js
// ๐Ÿ‘‡๏ธ with Mutation const arr1 = ['Alice', 'Bob', 'Charlie']; arr1[0] = 'John'; console.log(arr1); // ๐Ÿ‘‰๏ธ ['John', 'Bob', 'Charlie'] // ๐Ÿ‘‡๏ธ without Mutation ------ const arr2 = ['Alice', 'Bob', 'Charlie']; const newArr = ['Replacement Here', ...arr2.slice(1)]; console.log(newArr); // ๐Ÿ‘‰๏ธ ['Replacement Here', 'Bob', 'Charlie'] console.log(arr2); // ๐Ÿ‘‰๏ธ ['Alice', 'Bob', 'Charlie']

Our first example shows how to replace the first element in an array by using bracket notation [] to directly access the array element at index 0 and change its value.

Indexes are zero-based in JavaScript, meaning the first array element has an index of 0 and the last - an index of array.length - 1.

Assigning a new value to the array element at index 0 changes the contents of the original array. If you don't want to change the array, use the second approach instead.

The second example uses the spread operator (...) and the Array.slice method to get a new array containing the replacement, without changing the original array.

The parameter we passed to the slice method is the start index - the index of the first element to be included in the new array.

The slice method returns a new array, without changing the original array.

An easy way to think about the spread operator (...) is that we are taking the elements from the array and unpacking them into the new array.

Make sure to include the replacement element before the call to the slice method as the order gets preserved in the new array.

This is a more indirect way to replace the first element of an array, however it doesn't change the contents of the original array, which is what you want most of the time.

Mutations are difficult to track and reason about in a code base, especially when the same array or object is mutated multiple times at different places.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee