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"];
  2.  
  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"];
  2.  
  3. fruits_4.shift();
  4. console.log(fruits_4) // (3) ["banana", "orange", "grapes"]
webdevetc profile pic
webdevetc

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



More...


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 hide directory listing in .htaccess?

How to exclude URLs from the Laravel CSRF protection?

What is the difference between empty(), isset(), != null, is_null() in PHP

How to split a string into an array, in JS

How to group a SQL statement in brackets/parenthesis

How to merge/concat two arrays together in JS?

How to set the Expires header in .htaccess

How do you run a PHP script from the command line?

What is an example of an object literal?

An overview of every main PHP array function