Here are 5 ways to append an element to an array in JavaScript:
- Using array push()
- Using array splice()
- Using array unshift()
- Using array concat()
- Using spread operator
Method 1: Using array push()
The array push() is used to append an element at the end of an array.
Syntax
array.push(element1, element2,..., elementn)
Visual Representation
Example
dark = ['jonas', 'martha', 'claudia'];
console.log('Before using push: ', dark);
dark.push('ulrich');
console.log('After using push: ', dark);
Output
Before using push: [ 'jonas', 'martha', 'claudia' ]
After using push: [ 'jonas', 'martha', 'claudia', 'ulrich' ]
Method 2: Using array splice()
The array splice() method is used to add, remove, or replace elements from an array.
Visual Representation
Syntax
array.splice(index, howmany, item1, ....., itemX)
Example
let dark = ['jonas', 'martha', 'claudia'];
console.log('Before using splice: ', dark);
dark.splice(1, 0, 'ulrich');
console.log('After using splice: ', dark);
Output
Before using splice: [ 'jonas', 'martha', 'claudia' ]
After using splice: [ 'jonas', 'ulrich', 'martha', 'claudia' ]
The code inserts ‘ulrich’ at the first index (which is the second position) of the dark array.
Method 3: Using array unshift()
To append an element at the start of the Array, you can use the array unshift() method.
Visual Representation
Syntax
array.unshift(item1, item2, ..., itemX)
Example
let dark = ['jonas', 'martha', 'claudia'];
console.log('Before using unshift: ', dark);
dark.unshift('ulrich', 'mikkel');
console.log('After using unshift: ', dark);
Output
Before using unshift: [ 'jonas', 'martha', 'claudia' ]
After using unshift: [ 'ulrich', 'mikkel', 'jonas', 'martha', 'claudia' ]
Method 4: Using array concat()
The array concat() method joins two or more arrays. It does not modify the existing arrays but returns a new array containing the values of the joined arrays.
Visual Representation
Syntax
array1.concat(array2, array3, ..., arrayX)
Example
let dark1 = ['jonas', 'martha', 'claudia']
let dark2 = ['ulrich', 'mikkel']
let dark3 = ['helge', 'adam', 'noah']
let cast = dark1.concat(dark2, dark3)
console.log(cast)
Output
[
'jonas', 'martha',
'claudia', 'ulrich',
'mikkel', 'helge',
'adam', 'noah'
]
Method 5: Using spread operator
With the new ES6 spread operator, merging two arrays becomes even more comfortable.
Visual Representation![Visual Representation of Using spread operator](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%201024%20478'%3E%3C/svg%3E)
Syntax
let variable_name = [...value];
Example
let dark1 = ['jonas', 'martha', 'claudia'];
let dark2 = ['ulrich', 'mikkel'];
let finalArr = [...dark1, ...dark2];
console.log(finalArr);
Output
[ 'jonas', 'martha', 'claudia', 'ulrich', 'mikkel' ]
That is it.
Arjun
I can see someones been watching Dark on Netflix 😀