How to Add Remove Items from Javascript Array

  41 views   1 month ago Javascript

There are four basic methods that allow us to add or remove elements from an array:

  • push()
  • pop()
  • unshift()
  • shift()

push() Method

The array.push() method appends items to the end of an array. It accepts a list of items as an argument, and modifies an array by adding the items to the end of it, and then it returns the length of the modified array.

Syntax
array.push(...items);
Example
// define an array
let numbers = [1, 2, 3, 4, 5];

// add 6 to the end of the array.
numbers.push(6);

console.log(numbers); // [1, 2, 3, 4, 5, 6]

// you're not limited to one item
numbers.push(7, 8, 9, 10);

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

pop() Method

The array.pop() the method removes an item from the end of an array. It returns the item that is removed from the array.

Syntax
array.pop();
Example
// define an array
let numbers = [1, 2, 3, 4, 5];

// removes 5 from the end of the array.
let removedItem = numbers.pop();

console.log(numbers); // [1, 2, 3, 4]

// the items removed from the array
console.log(removedItem); // 5

unshift() Method

The array.unshift() method prepends items to the beginning of an array. It accepts a list of items as arguments and modifies the array by adding the items to the beginning of it, and then it returns the length of the modified array.

Syntax
array.unshift(...items);
Example
// define an array
let numbers = [1, 2, 3, 4, 5];

// add 0 to the beginning of the array.
numbers.unshift(0);

console.log(numbers); // [0, 1, 2, 3, 4, 5]

// you're not limited to one item
numbers.unshift(-3, -2, -1);

console.log(numbers); // [-3, -2, -1, 0, 1, 2, 3, 4, 5]

shift() Method

The array.shift() the method removes an item from the beginning of an array. It returns the item that is removed from the array.

Syntax
array.shift();
Example
// define an array
let numbers = [1, 2, 3, 4, 5];

// removes 1 from the end of the array.
let removedItem = numbers.shift();

console.log(numbers); // [2, 3, 4]

console.log(removedItem); // 1

I hope it can help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]