What is array unshift() in Javascript?

Overview

The unshift function in Javascript adds items to the start of an array. The general syntax shown below allows you to use the unshift function.

array.unshift(item1,item2)

Parameters

The unshift function takes the new items that should be added to the start of the array as a mandatory input.

Return value

The unshift function returns the length of the new array after the new items are added to the beginning of the array.

Example

The example below will help you understand the unshift function better. First, we define an array with days of the week, which are Wednesday, Thursday, and Friday. Then, we want to add the days Monday and Tuesday to the beginning of the array. We use the unshift function to do so, as shown below.

const days = ["Wednesday", "Thursday", "Friday"];
const ret = days.unshift("Monday","Tuesday");
console.log(ret)
console.log(days)

It must be noted that the order of insertion into the array plays a significant role. If you insert n items at once or insert one item n times, it will not result in the same array. This can be seen in the example below where, despite inserting numbers in the same order, the two methods of insertion result in different arrays.

const nums = [1,2,3];
const ret1 = nums.unshift(-1,0);
const nums2 = [1,2,3];
const ret2 = nums2.unshift(-1);
const ret3 = nums2.unshift(0);
console.log(nums)
console.log(nums2)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved