The Wayback Machine - https://web.archive.org/web/20240828170752/https://www.geeksforgeeks.org/how-to-add-elements-to-the-end-of-an-array-in-javascript/
Open In App

How to Add Elements to the End of an Array in JavaScript ?

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Appending elements to the end of an array is a fundamental task in JavaScript, essential for data manipulation and management. This guide will provide an overview of various methods to achieve this, enhancing your coding efficiency.

Importance of Adding Elements to an Array

Adding elements to an array is crucial for:

  • Building and modifying datasets dynamically.
  • Implementing queue and stack operations.
  • Enhancing functionality in applications that require data storage and retrieval.

There are several methods that can be used to add elements to the end of an array in JavaScript, which are listed below:

We will explore all the above methods along with their basic implementation with the help of examples.

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);

Output
[ 1, 2, 3, 4 ]
[
  10, 20, 30, 40,
  50, 60, 70
]

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);

Output
[ 1, 2, 3, 4, 5 ]

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);

Output
[ 1, 2, 3, 4, 5 ]

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);

Output
[ 1, 2, 3, 7, 4, 5 ]

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);

Output
[ 1, 2, 3, 4, 5 ]

6. Using a loop

Using a loop, you can add multiple elements to the end of an array in JavaScript. Iterate through the elements to be added and assign each to the next available index in the array using its length. This appends the new elements sequentially.

Example:

JavaScript
let arr = [1, 2, 3];
let elementsToAdd = [4, 5];

for (let i = 0; i < elementsToAdd.length; i++) {
  arr[arr.length] = elementsToAdd[i];
}

console.log(arr); 

Output
[ 1, 2, 3, 4, 5 ]

7. Using apply() Method

The apply() method in JavaScript allows you to call a function with a given this value, and arguments provided as an array. You can use this to add elements to the end of an array by combining the original array with new elements.

Example: In this example, we use the apply() method to add multiple elements to the end of the array

JavaScript
let numbers = [1, 2, 3];
let elementsToAdd = [4, 5];
Array.prototype.push.apply(numbers, elementsToAdd);
console.log(numbers);

Output
[ 1, 2, 3, 4, 5 ]




Previous Article
Next Article

Similar Reads

Javascript Program to Split the array and add the first part to the end | Set 2
Given an array and split it from a specified position, and move the first part of array add to the end.   Examples:   Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation :
2 min read
What is the difference between Front-End and Back-End Web Development?
A Website without visitors is like a ship lost in the horizon! And it is the combination of both Front-End and Back-End Web Development that ensures this ship is never lost!!! However, there is a lot of confusion that prevails over this topic. And if you are a beginner in this field, I am sure you are very confused about all these terms and what th
5 min read
CSS | border-end-end-radius Property
The border-end-end-radius property in CSS is used to specify the logical border-radius at the block-end border. It is adjustable with the element's writing-mode, direction, and text-orientation. Syntax: border-end-end-radius: length | percentage; Property values: length: This property hold the border radius length in specific unit. percentage: This
1 min read
AngularJS End to End (E2E) Testing Protractor Installation and Setup
The Protractor is an end-to-end test framework developed for Angular and AngularJS applications. It runs tests against the application interacting with it as a real user would, running in a real browser. Features of Protractor: Tests using browser: Protractor uses native events and browser-specific drivers to interact with the application.Build for
2 min read
AngularJS End to End (E2E) Testing | Protractor
Protractor is an end-to-end test framework developed for Angular and AngularJS applications. It run tests against the application interacting with it as a real user would, running in a real browser. In this article, we are going to create a basic test. Pre-requisite: Installation and Setup of Protractor Approach: We are going to create a basic test
2 min read
How to connect ReactJS as a front-end with PHP as a back-end ?
Connecting the front end of React with the PHP backend is a classic approach to building a web application with the front end for the user interface and the back end or server side for handling databases, programming logic, and other operations. React JSReact JS is a declarative, efficient, and flexible JavaScript library for building user interfac
3 min read
How to remove n elements from the end of a given array in JavaScript ?
In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript. We can remove n elements from the end of a given array in the following ways: Table of Content Using splice() MethodUsing pop() MethodUsing filter() MethodUsing Array slice() methodUsing while loopUsing the length PropertyMethod 1: Using
4 min read
How to move specified number of elements to the end of an array in JavaScript ?
The purpose of this article is to move some specified elements to the end of an array using JavaScript. Given an array of length say N, move some specified amount of elements say X to the end of the given array. Input: arr = [1, 2, 3, 4, 5]X = 2Output: The following array should be the output as the first two numbers are moved to the end of the arr
3 min read
Adding elements to the end of the array using filters in Vue.js
In this article, we are going to learn how to add elements to the end of an array in VueJS. Vue is a progressive framework for building user interfaces. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object
2 min read
Add Elements to a JavaScript Array
JavaScript Arrays are a fundamental data structure in JavaScript, providing a flexible way to store and manage collections of values. Add elements to a JavaScript Array is a common operation in programming. There are different methods to add elements to the JavaScript array, which are described below Methods to Add Elements to a JavaScript ArrayFol
3 min read
How to add elements to an existing array dynamically in JavaScript ?
An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type. In this article, we will see how to add new elements to an existing array dynamically in Javascript. We will discuss two methods in this article i.e. push() method and dynamically adding an element at any index using the index of the array. Examp
4 min read
Add new elements at the beginning of an array using JavaScript
In this article, we will learn how to add new elements at the beginning of an array using JavaScript. We can do this by using the following methods: Table of Content Using the Array unshift() MethodUsing Array splice() MethodUsing the Spread OperatorUsing Array concat() MethodUsing Array.prototype.copyWithin() MethodUsing Array.prototype.reduceRigh
4 min read
Javascript Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples:   Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9} Output: 1 9 8 4 2 7 6 9 0 0 0 0 0
2 min read
Javascript Program to Move all zeroes to end of array
Given an array of random numbers, Push all the zero's of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).Example:   Input :
3 min read
How to create an array of elements, ungrouping the elements in an array produced by zip in JavaScript ?
We can create an array of elements by ungrouping the elements in an array produced by zip by using different methods in JavaScript such as Math.max(), array specific methods namely Array.prototype.map(), Array.prototype.reduce() and Array.prototype.forEach(). This operation can also be termed as unzip. Before looking at unzip, let us understand wha
2 min read
How to add HTML elements dynamically using JavaScript ?
We learn how to add HTML elements dynamically using JavaScript. A basic understanding of HTML, CSS, and JavaScript is required. Here we are going to use a button and by clicking this button, we can add an HTML element dynamically in this example. Below are the approaches used to add HTML elements dynamically using JavaScript : Table of Content Usin
2 min read
How to add custom styles and ways to add custom styles in Tailwind-CSS ?
Tailwind is a popular CSS framework that makes your User Interface design making the process easier. It provides low-level classes and those classes combine to create styles for various components. Tailwind-CSS comes with a bunch of predefined styling but as a developer, we need more custom styling and the styles offered by tailwind are not enough
3 min read
Difference between “git add -A” and “git add”
When working with Git, the git add command is used to move changes from your working directory to the staging area. However, there are different options and flags that can be used with git add, such as -A, which might lead to some confusion. In this article, we'll explore the differences between git add -A and git add. 1. Git add- CommandThe git ad
2 min read
JavaScript Get the start and end of the day in UTC
Given a date, and the task is to determine the start and end of the day of the date using JavaScript. We're going to discuss a few methods. These are: JavaScript setHours() Method: This method sets the hour of a date object. This method can be used to set the minutes, seconds, and milliseconds. Syntax: Date.setHours(hour, min, sec, millisec) Parame
3 min read
How to create previous and next button and non-working on end position using JavaScript ?
In this article, the task is to create the previous and next button that doesn't work on the end positions with the help of JavaScript. Approach: Here we are going to add a disabled attribute to the pre button when it is at the start position which is 1 for us and remove the disabled attribute when it is not at the start (1) position.And same for t
2 min read
How to get the sum of the powers of all the numbers from start to end in JavaScript ?
Given three variables as Starting, Ending, and Power. Our task is to find the total sum of all the numbers between Starting and Ending inclusion to both ends raised to power. Example 1: Starting variable 1 End 5 and Power 2. Iterate from 1 to 5 and raised each to the power of 2. Add all elements 1+4+9+16+25 which is 55. Input: 1, 5, 2 Output: 55 Ex
3 min read
Javascript Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
5 min read
Javascript Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second cha
2 min read
Javascript Program For Moving All Occurrences Of An Element To End In A Linked List
Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -&gt; 2 -&gt; 2 -&gt; 4 -&gt; 3 key = 2 Output : 1 -&gt; 4 -&gt; 3 -&gt; 2 -&gt; 2 Input : 6 -&gt; 6 -&gt; 7 -&gt; 6 -&gt; 3 -&gt; 10 key = 6 Output : 7 -&gt;
6 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
5 min read
How Much JavaScript is Required to Become Front End Developer?
Front-end Development is the part of web development that is focused on the user end of a website or web application. It involves the development of elements that provides the interaction between the user and browsers. HTML, CSS, and JavaScript are the main components used by front-end developers. HTML is used for the structure of the page, CSS is
8 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
How to place cursor position at end of text in text input field using JavaScript ?
In this article, we are going to learn about how to place the cursor at the end of the text in a text input element using JavaScript.  At first, we are going to create a text input box where some value will be given and a button to place the cursor at the end. We can place the cursor at the end of the text in a text input element by using different
2 min read
JavaScript SyntaxError – Unexpected end of input
A SyntaxError: Unexpected end of input error in JavaScript occurs when the interpreter reaches the end of script it is reading and it indicates that the code is incomplete, this error will prevent the code from running and mostly happens when a closing bracket, quote or parenthesis are missing, here's how to understand this error, its causes and ho
3 min read
Top 10 Javascript Alternatives For Front-End Developers
Everything over the web is in JavaScript. Javascript is the most used programming language with approximately 97% of websites using JavaScript as a client-side programming language. Everything around us is Javascript ranging from iPhones, Macs, Androids, OS, Linux, etc. Learning and understanding the language helps create the most complex applicati
9 min read