You are on page 1of 3

shift()

The shift() method removes the first item of an array.

The shift() method changes the original array.

The shift() method returns the shifted element.

Syntax
array.shift()

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(“at first print the original array”);

console.log(fruits);

fruits.shift();

console.log(“after using shift methor the array will be”);

console.log(fruits);

o/p:-

"Orange", "Apple", "Mango"

unshift()
The unshift() method adds new elements to the beginning of an array.

The unshift() method overwrites the original array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(“at first print the original array”);

console.log(fruits);
fruits.unshift("Lemon","Pineapple");

console.log(“after using unnshift methor the array will be”);

console.log(fruits);

o/p:- "Lemon","Pineapple","Banana", "Orange", "Apple", "Mango"

splice()
The splice() method adds and/or removes array elements.

The splice() method overwrites the original array.

Syntax
array.splice(index, howmany, item1, ....., itemX)

Parameter Description

index Required.
The position to add/remove items.
Negative value defines the position from the end of the array.

howmany Optional.
Number of items to be removed.

item1, ..., item Optional.


X New elements(s) to be added.

Example1:-

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At position 2, add 2 elements:


fruits.splice(2, 0, "Lemon", "Kiwi");

console.log(fruits);

o/p:- ["Banana", "Orange" ,"Lemon", "Kiwi", "Apple", "Mango"]

Example2:-

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];

// At position 2, remove 2 items:

fruits.splice(2, 2);

console.log(fruits);

o/p:- "Banana" ,"Banana" ,"Kiwi"

You might also like