Last updated: Oct 26, 2021
Check out my new book
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 = 'replacement'.
// 👇️ with Mutation const arr1 = ['Alice', 'Bob', 'Charlie']; arr1 = '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
 to directly access the array element at index
change its value.
0and 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
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.
slice method returns a new array, without changing the original array.
Make sure to include the replacement element before the call to the
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.