Adding an element at the end of the array in Javascript


In this article, we are going to add an at the end of the array in JavaScript.

An array is a special variable, which can hold more than one value.

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items together. This makes it easier to calculate the position of each element by simply adding an offset to a base value of the memory location of the first element of the array. The base value is index 0 for the first element in the array and the difference between the two indexes is the offset.

Syntax

Following is the syntax for the array data structure in JavaScript.

const array = ["Value1", "Value2", "Value3"];

Arrays allow random access to elements. This makes accessing elements by position faster and easy. Arrays have better cache locality which makes a pretty big difference in performance. Arrays represent multiple data items of the same type using a single name, instead of storing different items in different variables.

Adding Array Elements at the End

We use push() function to add an element. The function adds the element at the end.

Syntax

Following is the syntax for the adding an element at the end of the array in JavaScript.

array.push(item)

Example

Following is the example program for adding an element at the end of the array in JavaScript.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = [0,1,2,3,4,5] arr1.push(6) document.write(arr1) </script> </body> </html>

We can add all type of data to the array.

Example

Following is the example program to add an element at the end of the array.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = ['Ram','Hari','Yadav'] arr1.push("lokesh") document.write(arr1) </script> </body> </html>

Example

Following is another example program for adding an element at the end of the array in JavaScript.

<!DOCTYPE HTML> <html> <head> </head> <body> <script > const arr1 = [0, 1, 2, 3, 4, 5] const arr2 = [6, 7, 8, 9, 10]; const concatedArray = arr1.concat(arr2); concatedArray.push(10000) document.write(concatedArray) </script> </body> </html>

Updated on: 21-Nov-2022

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements