There are various ways to add or append an item to an array. We will make use of push, unshift, splice, concat, spread and index to add items to array. Let’s discuss all the 6 different methods one by one in brief.

  • The push() method
  • The unshift() method
  • The splice() method
  • The concat() method
    • Passing array as parameter
    • Passing value as parameter
  • The spread(…) operator
  • Adding element with index

The push() method

This method is used to add elements to the end of an array. This method returns the new array length.

const movies = ['Avengers', 'Iron-man', 'Thor'];
​
const newLength = movies.push('Hulk'); 
​
console.log(movies); // ['Avengers', 'Iron-man', 'Thor', 'Hulk'];
​
console.log(newLength); //4

We can also add multiple values with push method.

const movies = ['Iron-man', 'Thor'];
​
movies.push('Avengers', 'Deadpool', 'Hulk');
​
console.log(movies); // ["Iron-man", "Thor", "Avengers", "Deadpool", "Hulk"]

The unshift() method

The unshift() method is used to add elements at the beginning of an array. This method returns the new array length.

const cars = ['Audi', 'BMW', 'Jaguar'];
​
const newLength = cars.unshift('Mercedes'); 
​
console.log(newLength ); // 4
​
console.log(cars); // ['Mercedes', 'Audi', 'BMW', 'Jaguar']

We can also add multiple values with unshift() method.

const cars = ['Audi', 'Jaguar'];
​
cars.unshift('Mercedes', 'Tesla'); 
​
console.log(cars); // ['Mercedes', 'Tesla', 'Audi', 'Jaguar']

#javascript #programming #developer

6 Ways Add Items to an Array in JavaScript
3.40 GEEK