To add a new value to the beginning of the JS array, you can use the function Array.unshift
. Here’s how it works.
const arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [ 0, 1, 2, 3 ]
Array.unshift
works with multiple arguments.
const arr = [1, 2, 3];
arr.unshift(-2, -1, 0);
console.log(arr); // [ -2, -1, 0, 1, 2, 3 ]
Alternatively, you can append new values to the end of the JavaScript array using the function Array.push
.