How to add and remove items to an array in JS?

JavaScript: How to add and remove items to an array in JS?

If you want to add items to an array in javascript, you can use the push() method to add it to the end of an array.

  1. let fruits = ["apple","banana","orange","grapes"];
  2. fruits.push("kiwi"); //kiwi will be the last item (after grapes) in the array

Or to add it to the start of an array, use unshift.

  1. let fruits_2 = ["apple","banana","orange","grapes"];
  2. fruits_2.unshift("kiwi"); // kiwi will be the first item in the array (before apple)

How to remove items from JS arrays?

You can use .pop() and .unshift().

Using pop() to remove items from Javascript arrays

To remove an item from the end of an array, you use .pop():

  1. let fruits_3 = ["apple","banana","orange","grapes"];
  3. fruits_3.pop();
  4. console.log(fruits_3) // (3) ["apple", "banana", "orange"]

Using unshift() to remove items from a JS array

To remove an item from the start of an array, you use .unshift():

  1. let fruits_4 = ["apple","banana","orange","grapes"];
  3. fruits_4.shift();
  4. console.log(fruits_4) // (3) ["banana", "orange", "grapes"]
webdevetc profile pic

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This ( is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.


Comments and discussion about How to add and remove items to an array in JS?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to review blog posts (written by other users) before they get published on your WordPress blog?

A list of operators on Eloquent's where() method

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to block an IP range based on CIDR in Apache with .htaccess

What kind of database field type should you (normally) use for foreign keys?

How to query mysql using PDO in PHP?

How to check if a relation was loaded on an Eloquent model already?

How to eager load multiple levels of relationships in Eloquent?

How to set up an alias to map one directory to another destination

How to find the average value of items in a Laravel Collection?