In JavaScript, the unshift() method is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.
Syntax:
array.unshift(element1, element2, ..., elementN)
- array: The array to which elements will be added.
- element1, element2, ..., elementN: Elements to be added to the beginning of the array.
Example:
let fruits = ['banana', 'orange'];
let newLength = fruits.unshift('apple', 'grape');
console.log(newLength); // Output: 4
console.log(fruits); // Output: ['apple', 'grape', 'banana', 'orange']
Explanation:
- In the example, unshift('apple', 'grape') adds the elements 'apple' and 'grape' to the beginning of the fruits array.
- The unshift() method modifies the original array ('fruits') by adding the new elements to its beginning.
- The method returns the new length of the array after the elements have been added.
The unshift() method provides a convenient way to add elements to the beginning of an array, making it useful for dynamic data manipulation in JavaScript.