The Array.unshift()
method is a built-in JavaScript function that adds one or more elements to the beginning of an array and returns the new length of the array. This method is useful when you need to prepend elements to an array.
Syntax
arr.unshift(element1, element2, ..., elementN);
Parameters
Parameter | Description |
---|---|
element1, …, elementN | (Required) The elements to be added to the beginning of the array. |
Return Value
The method returns the new length of the array after the elements have been added.
Example 1: Adding a Single Element
let arr = [20, 30, 40, 50]; arr.unshift(10); console.log(arr); // Output: [ 10, 20, 30, 40, 50 ] console.log(arr.length); // Output: 5
Example 2: Adding Multiple Elements
let arr = [30, 40, 50]; let newLength = arr.unshift(10, 20); console.log(arr); // Output: [ 10, 20, 30, 40, 50 ] console.log(newLength); // Output: 5
Example 3: Using unshift()
with an Empty Array
let arr = []; let newLength = arr.unshift(10); console.log(arr); // Output: [ 10 ] console.log(newLength); // Output: 1
Example 5: Adding Objects to an Array
let users = [{ name: 'John' }]; users.unshift({ name: 'Alice' }); console.log(users); // Output: [{ name: 'Alice' }, { name: 'John' }]
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |