In this article, we are going to learn about adding elements to the end of an array in JavaScript, Adding elements to the end of an array in JavaScript means appending new values after the last existing element.
There are several methods that can be used to add elements to the end of an array in JavaScript, which are listed below:
- Using push() Method
- Using spread(…) Operator
- Using concat() Method
- Using the length Property
- Using splice() Method
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using push() Method
The JavaScript Array push() Method is used to add one or more values to the end of the array. This method changes the length of the array by the number of elements added to the array.
Syntax:
arr.push(element0, element1, … , elementN)
Example: In this example, we are using the push() method to add a new element in the last index of the array.
Javascript
const num1 = [1, 2, 3]; num1.push(4); console.log(num1); // adding multiple element i the last index of array const num2 = [10, 20, 30, 40, 50]; num2.push(60, 70); console.log(num2); |
[ 1, 2, 3, 4 ] [ 10, 20, 30, 40, 50, 60, 70 ]
Approach 2 : Using Spread (…) Operator
Using the spread (…) operator, you can add elements to the end of an array by creating a new array and combining the original array with the new elements.
Syntax:
let variablename1 = [...value];
Example: In this example, we are using the spread(…) operator to add an element in the last index of our given array.
Javascript
let numbers = [1, 2, 3]; let newNumbers = [...numbers, 4, 5]; console.log(newNumbers); |
[ 1, 2, 3, 4, 5 ]
Approach 3: Using concat() Method
In this approach, Using the concat() method, create a new array by combining the original array with additional elements. It does not modify the original array, giving a clean way to add elements.
Syntax:
let newArray = oldArray.concat(value1 , [ value2, [ ...,[ valueN]]])
Example:
Javascript
const numbers = [1, 2, 3]; const newNumbers = numbers.concat(4, 5); console.log(newNumbers); |
[ 1, 2, 3, 4, 5 ]
Approach 4: Using the length Property
In this approach, we are Using the length property, you can add elements to the end of an array by assigning values to indexes equal to the current length, effectively extending the array with new elements.
Syntax:
array.length = number
Example:
Javascript
let numbers = [1, 2, 3, 7]; numbers[numbers.length] = 4; numbers[numbers.length] = 5; console.log(numbers); |
[ 1, 2, 3, 7, 4, 5 ]
Approach 5: Using splice() Method
Using the splice() method, you can add elements to the end of an array by specifying arr.length as the index and setting the number of elements to remove to 0. It directly modifies the original array.
Syntax:
Array.splice( index, remove_count, item_list )
Example: In this example we are using above-explained approach.
Javascript
let numbers = [1, 2, 3]; numbers.splice(numbers.length, 0, 4, 5); console.log(numbers); |
[ 1, 2, 3, 4, 5 ]