Comment on page
Add Item
4 methods to add items to an Array in JavaScript
push()
will add the element(s) to the end of the array and return the new length of the array.const arr = [10,11];
const val = arr.push(12,13);
console.log({arr, val});
Output:
{arr: [10,11,12,13], val: 4}
unshift()
will add the element(s) to the beginning of an array and return the new length of the array.const arr = [10,11];
const val = arr.shift(12,13);
console.log({arr, val});
Output:
{arr: [12,13,10,11], val: 4}
splice(start, deleteCount, item1..itemN)
will remove deleteCount
of elements starting at index start
and returns an array containing the deleted elements.- start - the zero-based index at which to start.
- deleteCount - an integer indicating the number of elements to remove. For add, set this to zero.
- item1..itemN - The items to add at the
start
index.
const arr = [10,11];
const val = arr.splice(1,0,12,13);
console.log({arr, val});
Output:
{arr: [10,12,13,11], val: []}
- arr1..arrN - Arrays and/or values to be concatinated.
const arr = [10,11];
const val = arr.concat([12,13], 14);
console.log({arr, val});
Output:
{arr: [10,11], val: [10,11,12,13,14]}
concat()
does not modify the original array, but instead creates a shallow copy.Last modified 1mo ago