Skip to main content

JavaScript Array unshift Method (Live Playground)

The unshift method in JavaScript allows you to add one or more elements to the beginning of an array.

Here's a basic example:

let fruits = ['apple', 'banana', 'mango'];

fruits.unshift('kiwi');

console.log(fruits);
// Expected output: ["kiwi", "apple", "banana", "mango"]

In this instance, the unshift method adds "kiwi" to the start of the fruits array. The unshift method then returns the new length of the array.

Live Playground, Try it Yourself

The unshift method can accept multiple arguments, enabling you to add multiple elements:

let fruits = ['apple', 'banana', 'mango'];

fruits.unshift('kiwi', 'orange');

console.log(fruits);
// Expected output: ["kiwi", "orange", "apple", "banana", "mango"]

In this case, "kiwi" and "orange" are added to the start of the fruits array. Keep in mind, the unshift method modifies the original array.

Live Playground, Try it Yourself

In conclusion, the unshift method in JavaScript is a powerful tool for adding elements to the beginning of an array. By using unshift, you can dynamically alter the array, making it a versatile tool in your JavaScript toolkit.

Don't forget to practice using unshift with various arrays and arguments to deepen your understanding of how it operates!