How to Append an Element to Array in JavaScript

To append an element to an array in JavaScript, you can use the “array.push()” method. The array push() method inserts or appends an element to the array. It adds new elements to the end of an array and returns the new length.

let se_education = ["Otis", "Maeve", "Eric", "Adam"];

console.log("Before appending an element:", se_education)

se_education.push("Lilly");

console.log("After appending an element:", se_education)

Output

Before appending an element: [ 'Otis', 'Maeve', 'Eric', 'Adam' ]

After appending an element: [ 'Otis', 'Maeve', 'Eric', 'Adam', 'Lilly' ]

Here, we defined an array using square brackets and append an element using the push() function.

The push() function adds an element at the end of an array, as you can see in the output.

You can see that the push() method changes the array’s length.

What if you want to append an element at the end of an array? Well, let’s see how to do that.

Using unshift() method

To append elements at the beginning of an array, you can use the unshift()” method. The unshift() is a built-in JavaScript method that adds new elements to the beginning of an array and returns the new length.

let se_education = ["Otis", "Maeve", "Eric", "Adam"];

console.log("Before appending an element:", se_education)

se_education.unshift("Lilly");

console.log("After appending an element at the beginning:", se_education)

Output

Before appending an element: [ 'Otis', 'Maeve', 'Eric', 'Adam' ]

After appending an element at the beginning: [ 'Lilly', 'Otis', 'Maeve', 'Eric', 'Adam' ]

The “Lilly” element has been appended at the beginning of the array.

Using the array.concat() method

To append elements of one array to another in JavaScript, you can use the “array.concat()” method. The array concat() is a built-in method to join two or more arrays.

let se_education = ["Otis", "Maeve", "Eric", "Adam"];

let data = se_education.concat(["Lilly", "Anwar", "Aimee"]);

console.log("After concating:", data)

Output

After concating: [
'Otis', 'Maeve',
'Eric', 'Adam',
'Lilly', 'Anwar',
'Aimee'
]

With the spread operator, the original array will be unchanged, and it returns a new array with new elements appended, compliant with the quality of functional programming.

let se_education = ["Otis", "Maeve", "Eric", "Adam"];

let data = [
 ...se_education,
 "Lilly", "Anwar", "Aimee"];

console.log("After concating:", data)

Output

After concating: [
'Otis', 'Maeve',
'Eric', 'Adam',
'Lilly', 'Anwar',
'Aimee'
]

When …array is used in the function call, it ‘expands’ an iterable object array into the list of arguments.

As you can see, we get the same output as an array.concat() method.

That’s it.

Leave a Comment