Add/Remove item to/from Array in Javascript

add/remove items from start/end of an array

Subscribe to my newsletter and never miss my upcoming articles

In a simple definition, Javascript arrays are used to store multiple values in a single variable, which means, it can hold more than one value at a time.

For instance, if you have a list of items (a list of car names), storing the cars in a single variable could look like this:

let car1 = "BMW";
let car2 = "Ford";
let car3 = "Tesla";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name and you can access the values by referring to an index number. For example,

let cars = ["BWM", "Ford", "Tesla"];

In the following, I am going to explain all methods by the group in order to make things easier to remember.


This method add one or more elements to the end of the array and returns the new length of the array. For example,

const cars = ["BMW","Ford","Tesla"];
console.log(cars.push("Honda")): //output: 4
console.log(cars);  //output: '["BMW","Ford", "Tesla", "Honda"]'


This method removes the last element from the end of the array and returns that element.

const cars = ["BMW","Ford","Tesla"];
console.log(cars);  //output: '["BMW","Ford"]'


This method removes the first element from an array and returns that element.

const cars = ["BMW","Ford","Tesla"];
console.log(cars);  //output: '["Ford","Tesla"]'


This method adds one or more elements to the beginning of an array and returns the new length of the array

const cars = ["BMW","Ford","Tesla"];
console.log(cars.unshift("Honda")): //output: 4
console.log(cars);  //output: '["Honda", "BMW", "Ford", "Tesla"]'


This method returns a new array with specified start too end elements.

const cars = ["BMW","Ford","Tesla"];
const sliced = cars.slice(2,3);
console.log(slicked): //output: ["Tesla"];
console.log(cars): //output: '["BMW","Ford","Tesla"]'


This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

const car1 = ["BMW","Ford","Tesla"];
const car2 = ["Toyota", "Honda"];
const cars = car1.concat(car2);
console.log(cars); //output: '["BMW", "Ford", "Tesla", "Toyota", "Honda"]';
console.log(car1);//output: '["BMW","Ford","Tesla"]';
console.log(car2);//output: '["Toyota", "Honda"]';

Comments (2)

@thebarefootdev's photo

Good article! Don't forget the easiest implementation via ES6

// Add new items
const arr = ['a','b','c'];
const newItems = ['d','e','f']
const newArr = [...arr, ...newItems];

// remove items
const arrayWithRemovedItems = newArr
  .filter(i => !newItems.includes(i))

(it's always best to return a new array to be functional and to avoid memory leakage)

Nimatullah Razmjo's photo

Thanks 🙏. I will cover them in my next article