unshift() JavaScript Array Method – Prepend Items to an Array
Whenever you use unshift() on an array, the method does the following:
- It adds its arguments to the beginning of its calling array.
- It returns the calling array's new length.
note
- A calling array is an array on which you used
unshift()
. So, inbestColorsList.unshift()
,bestColorsList
is the calling array. unshift()
is sometimes written asArray.prototype.unshift()
because it is a method of theArray
object'sprototype
property.
Syntax of the unshift()
Method
unshift()
accepts one or more arguments. Here's the syntax:
callingArray.unshift(item1, item2, ..., itemX)
The item1, item2, ..., itemX
arguments signify the items you wish to add to the beginning of the calling array.
Examples of the unshift()
Method
Below are examples of the unshift()
method.
Add One New Item to the Beginning of an Array
// Define an array:
const numbersArray = [1, 2, 3, 4];
// Add a new item to the beginning of the numbersArray:
numbersArray.unshift(0);
// Check the numbersArray's current content:
console.log(numbersArray);
// The invocation above will return:
[0, 1, 2, 3, 4];
The snippet above used unshift()
to prepend an item (0
) to the beginning of the calling array.
Add Three New Items to the Beginning of an Array
const fruitsArray = ["Mango", "Apple"];
const totalFruits = fruitsArray.unshift("Orange", "Lemon", "Grape");
console.log(fruitsArray);
// The fruitsArray's invocation above will return:
["Orange", "Lemon", "Grape", "Mango", "Apple"];
console.log(totalFruits);
// The totalFruits' invocation above will return: 5
In the snippet above, the totalFruits
' invocation returned 5
because unshift()
returned the calling array's new length.
note
Overview
This article discussed what JavaScript's unshift()
method does. We also used examples to see how it works.
Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.
Tweet this article