Adding and removing items from arrays in JavaScript

In JavaScript, you can use functions to add and remove items from an array. Here are some commonly used methods:

Adding Items:

  1. push(): Adds one or more elements to the end of an array and returns the new length of the array.
  2. unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
  3. splice(): Allows you to add elements at any position in an array.

Removing Items:

  1. pop(): Removes the last element from an array and returns that element.
  2. shift(): Removes the first element from an array and returns that element.
  3. splice(): Can also be used to remove elements from an array at any position.

Remember, splice() can both add and remove items depending on how it's used. It's a versatile method.

Adding an item to the end of an array (push()):

The push() method adds one or more elements to the end of an array and returns the new length of the array.

In the example, 'Date' is added to the end of the products array.

 
 // Example 1: Adding an item to the end of an array
 let products = ['Apple', 'Banana', 'Cherry'];
 products.push('Date');
 // Result: ['Apple', 'Banana', 'Cherry', 'Date']
 

Adding an item to the beginning of an array (unshift()):

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. In the example, 'Apricot' is added to the beginning of the products array.

 

 
 let products = ['Apple', 'Banana', 'Cherry'];
 // Example 2: Adding an item to the beginning of an array
 products.unshift('Apricot');
 // Result: ['Apricot', 'Apple', 'Banana', 'Cherry']

 

Removing the last item from an array (pop()):

The pop() method removes the last element from an array and returns that element.

 
 
  let products = ['Apple', 'Banana', 'Cherry'];
 // Example 3: Removing the last item from an array
  products.pop();
 // Result: ['Apple', 'Banana']

Removing the first item from an array (shift()):

The shift() method removes the first element from an array and returns that element. 

 
 
 
  let products = ['Apple', 'Banana', 'Cherry'];
  // Example 4: Removing the first item from an array
  products.shift();
  // Result: ['Banana', 'Cherry']

Adding and removing items at specific positions (splice()):

The splice() method can be used to add or remove elements from an array at any position. The first argument is the starting position, the second argument is the number of elements to remove, and the rest of the arguments are the elements to add. In the example, at position 2, one element is removed ('Charlie') and two elements ('Chris' and 'Daniel') are added.

 
 // Example 5: Adding and removing items at specific positions
  let students = ['Alice', 'Bob', 'Charlie', 'David', 'Eve'];
  students.splice(2, 1, 'Chris', 'Daniel');
  // Result: ['Alice', 'Bob', 'Chris', 'Daniel', 'David', 'Eve']