Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding an element at the end of the array in Javascript
In JavaScript, adding elements to the end of an array is a fundamental operation. The most common and efficient method is using the push() method, which modifies the original array by appending one or more elements.
An array is a special variable that can hold multiple values in a single ordered collection. Arrays in JavaScript are dynamic, meaning you can add or remove elements after creation.
What is an Array?
An array is a collection of items stored at contiguous memory locations. Arrays allow random access to elements, making it faster to access elements by their position (index). They represent multiple data items using a single name and provide better cache locality for improved performance.
Syntax
Basic array declaration in JavaScript:
const array = ["Value1", "Value2", "Value3"];
Using push() Method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Syntax
array.push(element1, element2, ..., elementN)
Example: Adding Numbers
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script>
const arr1 = [0, 1, 2, 3, 4, 5];
arr1.push(6);
document.write("Array after push: " + arr1);
</script>
</body>
</html>
Array after push: 0,1,2,3,4,5,6
Example: Adding Strings
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script>
const names = ['Ram', 'Hari', 'Yadav'];
names.push("Lokesh");
document.write("Names array: " + names);
</script>
</body>
</html>
Names array: Ram,Hari,Yadav,Lokesh
Example: Adding Multiple Elements
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script>
const numbers = [1, 2, 3];
numbers.push(4, 5, 6);
document.write("Updated array: " + numbers);
document.write("<br>Array length: " + numbers.length);
</script>
</body>
</html>
Updated array: 1,2,3,4,5,6 Array length: 6
Key Points
- The
push()method modifies the original array - It returns the new length of the array
- You can add multiple elements in a single call
- Works with any data type: numbers, strings, objects, or arrays
Return Value
The push() method returns the new length of the array after adding elements:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script>
const fruits = ['apple', 'banana'];
const newLength = fruits.push('orange');
document.write("New length: " + newLength);
document.write("<br>Array: " + fruits);
</script>
</body>
</html>
New length: 3 Array: apple,banana,orange
Conclusion
The push() method is the most efficient way to add elements to the end of a JavaScript array. It modifies the original array and returns its new length, making it perfect for dynamically building arrays in your applications.
