In JavaScript, there are several ways to add elements to an array.

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

let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]

Using the unshift() method: This method adds one or more elements to the beginning of an array and returns the new length of the array.

let arr = [1, 2, 3];
arr.unshift(0); // [0, 1, 2, 3]

Using the splice() method: This method adds or removes elements from an array at a specified index and returns the removed elements, if any.

let arr = [1, 2, 3];
arr.splice(1, 0, 4); // [1, 4, 2, 3]

Using the spread operator: This operator allows you to add the elements of one array to another.

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combinedArr = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

These are the most common ways to add elements to an array in JavaScript. You can use any of these methods depending on your requirement.

Also Read:

Categorized in: