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

What is WordPress default Apache .htaccess rules?

How do Invokable Controllers work in Laravel?

What is the difference between integration and unit tests?

How to convert between types in JS?

How to output (echo/print) content in PHP

How to add the CSRF (Cross-site request forgery) token in Laravel?

What is the difference between reference and primitive data types types in Javascript?

What are Template literals (Template strings) in JS?

How to block IPv6 IP addresses in .htaccess

How to pick what array_intersect function to use in PHP?