JavaScript unshift() method


The unshift() method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array by inserting new elements at the start and returns the new length of the array.

Syntax:

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

Return Value:

  • Number: The new length of the array after the elements have been added.

Key Points:

  • Modifies the original array: The unshift() method changes the original array by inserting new elements at the front.
  • Returns the new length: It returns the updated length of the array.
  • Inserts multiple elements: You can add one or more elements at the start of the array.

Example 1: Adding one element to the array

let fruits = ['banana', 'orange']; let newLength = fruits.unshift('apple'); console.log(fruits); // ['apple', 'banana', 'orange'] console.log(newLength); // 3 (new length of the array)

Example 2: Adding multiple elements at once

let numbers = [3, 4, 5]; numbers.unshift(1, 2); console.log(numbers); // [1, 2, 3, 4, 5]

Example 3: Using unshift() with an empty array

let list = []; list.unshift('item1', 'item2'); console.log(list); // ['item1', 'item2']

Performance Consideration:

  • Time complexity: The time complexity of unshift() is O(n), where n is the number of elements in the array. This is because adding elements at the beginning requires shifting all existing elements to higher indices.

Summary:

  • unshift() adds one or more elements to the beginning of an array, modifying the original array. It returns the new length of the array and allows multiple elements to be added in a single call. However, it may be less efficient than adding elements to the end (using push()) for large arrays because existing elements need to be re-indexed.