js add to array in javascript

To add an element to an array in Javascript, we have multiple options:

  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 the spread operator: the spread operator allows us to spread an existing array into a new array and then add new elements.
index.tsx
let arr = [1,2,3];
let newArr = [...arr, 4];
console.log(newArr); // Output: [1, 2, 3, 4]
90 chars
4 lines
  1. Using indexing: you can also assign an element directly to a specific index to add elements to the array.
index.tsx
let arr = [1, 2, 3];
arr[3] = 4;
console.log(arr); // Output: [1, 2, 3, 4]
75 chars
4 lines

All three methods will give you the same output, adding the element 4 to the end of the array.

gistlibby LogSnag