add to array in javascript

To add an element to an array in JavaScript, there are multiple ways to accomplish this task.

  1. Using push() method: The push() method adds one or more elements to the end of an array and returns the new length of the array.
index.tsx
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
76 chars
4 lines
  1. Using spread operator: The spread operator(...) can also be used to add an element(s) to an array.
index.tsx
let arr = [1, 2, 3];
arr = [...arr, 4];
console.log(arr); // Output: [1, 2, 3, 4]
82 chars
4 lines
  1. Using concat() method: The concat() method is used to merge two or more arrays into one, but it can also be used to add an element(s) to an array.
index.tsx
let arr = [1, 2, 3];
arr = arr.concat(4);
console.log(arr); // Output: [1, 2, 3, 4]
84 chars
4 lines

gistlibby LogSnag