Home » JavaScript

Array push() method with example in JavaScript

JavaScript push() method: Here, we are going to learn about the push() method of array in JavaScript.
Submitted by IncludeHelp, on February 27, 2019

JavaScript push() method

push() method is used adds/inserts an element at the end of an array, it returns nothing but changes the length of the array.

Syntax:

    array_name.push(element1, element2, ...);

It accepts one or more than one elements and inserts to the end of the array and changed the length of an array.

Examples:

    Input:
    var countries = ["INDIA", "USA"];

    Function call:
    countries.push("UK");
    countries.push("CANADA", "RUSSIA");
    
    Output:
    "INDIA", "USA", "UK", "CANADA", "RUSSIA"

JavaScript Code to demonstrate example of Array.push() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var countries = ["INDIA", "USA"];
		document.write("countries: " + countries + "<br>");
		document.write("length is: " + countries.length + "<br>");
		
		//adding one element
		countries.push("UK");
		document.write("countries: " + countries + "<br>");
		document.write("length is: " + countries.length + "<br>");
		
		//adding two elements
		countries.push("CANADA", "RUSSIA");
		document.write("countries: " + countries + "<br>");
		document.write("length is: " + countries.length + "<br>");		
		
	</script>
</body>
</html>

Output

countries: INDIA,USA
length is: 2
countries: INDIA,USA,UK
length is: 3
countries: INDIA,USA,UK,CANADA,RUSSIA
length is: 5




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.