How to append array in javascript?

In JavaScript, you can append new elements to an existing array in several ways. Here are a few common approaches:

  1. Using the push() method: The push() method adds one or more elements to the end of an array and returns the new length of the array. Here’s an example:
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]

In this example, the push() method is used to append the number 4 to the end of the arr array.

  1. Using the spread operator: The spread operator (…) can be used to concatenate two arrays. Here’s an example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = [...arr1, ...arr2];
console.log(newArr); // Output: [1, 2, 3, 4, 5, 6]

In this example, the spread operator is used to concatenate arr1 and arr2 into a new array called newArr.

  1. Using the concat() method: The concat() method joins two or more arrays and returns a new array that contains all the elements from the original arrays. Here’s an example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = arr1.concat(arr2);
console.log(newArr); // Output: [1, 2, 3, 4, 5, 6]

In this example, the concat() method is used to concatenate arr1 and arr2 into a new array called newArr.

Note that all of these methods modify the original array in some way. If you want to create a new array that includes the original array plus the appended element(s), you can use the spread operator or concat() method to create a new array, like in the examples above.

Leave a Reply

Your email address will not be published. Required fields are marked *