JavaScript Array.unshift() Method Example

The JavaScript Array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Syntax

arr.unshift(element1[, ...[, elementN]])
Parameters: 
elementN - The elements to add to the front of the array. 
Return value: The new length property of the object upon which the method was called.

Example 1 - Adding elements to the front of the array

var progLangs = ['C++', 'PHP', 'Python'];

console.log(progLangs.unshift('Java', 'C'));

console.log(progLangs);
Output:
5
 ["Java", "C", "C++", "PHP", "Python"]

More Examples

let arr = [1, 2];

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

Comments