Middle
What methods are available for adding an element to an array?
sobes.tech AI
Answer from AI
In JavaScript (Frontend), there are several methods to add an element to an array:
push(element)— adds the element to the end of the array.unshift(element)— adds the element to the beginning of the array.splice(index, 0, element)— inserts the element at the specified position.
Example:
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.unshift(0); // [0, 1, 2, 3, 4]
arr.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4]
You can also use the spread operator to create a new array with an added element:
let newArr = [...arr, 5];