101 of 264 menu

unshift method

The unshift method adds an unlimited number of new elements to the beginning of an array. In this case, the original array is modified, and the new length of the array is returned as a result.

Syntax

array.unshift(element, element, element...);

Example

Let's add two more new elements to the beginning of an array and output the modified array:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.unshift('1', '2'); console.log(arr);

The code execution result:

['1', '2', 'a', 'b', 'c', 'd', 'e']

Example

Let's add two new elements and output the new length of an array:

let arr = ['a', 'b', 'c', 'd', 'e']; let length = arr.unshift('1', '2'); console.log(length);

The code execution result:

7

See also

  • the push method
    that adds elements to the end of an array
  • the shift and pop methods
    that remove elements from an array
  • the fill method
    that fills an array
byenru