add an element to the beginning of an array in javascript

To add an element to the beginning of an array in JavaScript, you can use the unshift() method. unshift() adds one or more elements to the beginning of an array, and returns the new length of the array.

Here's an example:

index.tsx
let myArray = [2, 3, 4];

myArray.unshift(1);

console.log(myArray); // Output: [1, 2, 3, 4]
93 chars
6 lines

In this example, we add the number 1 to the beginning of the myArray array using the unshift() method. The resulting array is [1, 2, 3, 4].

related categories

gistlibby LogSnag