menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:unshift() Method

menu

In JavaScript, the unshift() method is used to add one or more elements to the beginning of an array. It modifies the original array by inserting the specified values at the beginning and returns the new length of the array after the addition.

Here's the basic syntax of the unshift() method:

javascriptarray.unshift(element1, element2, ..., elementN);
  • array: The array to which you want to add elements at the beginning.

  • element1, element2, ..., elementN: The elements you want to add to the beginning of the array.

Here's an example of how unshift() works:

javascriptconst fruits = ['banana', 'cherry'];

const newLength = fruits.unshift('apple', 'date');

console.log(fruits);      // Outputs: ['apple', 'date', 'banana', 'cherry']
console.log(newLength);   // Outputs: 4 (the new length of the array)

In this example, the unshift() method adds the elements 'apple' and 'date' to the beginning of the fruits array, and the new length of the array is returned, which is 4.

You can use the unshift() method to dynamically add elements to the beginning of an array, effectively shifting all existing elements to higher indices. This is useful when you want to prepend items to an array.

1280 x 720 px