Home » JavaScript

Array shift() method with example in JavaScript

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

JavaScript shift() method

shift() method is used to remove the first element of an array and returns the deleted element.

It changes the array length.

Syntax:

    array_name.shift();

Parameters: None

Return value: It returns a type of value that array contains, it actual returns deleted the element.

Example:

    Input:
    var arr1 = [10, 20, 30, 40, 50];

    Function call:
    arr1.shift();
    
    Output:
    20, 30, 40, 50

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

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

<body>
	<script>
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = ["Amit", "Ankur", "Akash"];
		
		//printing arrays before the deleting elements
		document.write("arr1: " + arr1 + "<br>");
		document.write("arr1 length: " + arr1.length + "<br>");
		document.write("arr2: " + arr2 + "<br>");
		document.write("arr2 length: " + arr2.length + "<br>");
		
		//removing element
		arr1.shift();
		arr1.shift();		
		arr2.shift(); 
		document.write("<br>After removing...<br><br>");
		document.write("arr1: " + arr1 + "<br>");
		document.write("arr1 length: " + arr1.length + "<br>");
		document.write("arr2: " + arr2 + "<br>");
		document.write("arr2 length: " + arr2.length + "<br>");		
		
	</script>
</body>
</html>

Output

arr1: 10,20,30,40,50
arr1 length: 5
arr2: Amit,Ankur,Akash
arr2 length: 3

After removing...

arr1: 30,40,50
arr1 length: 3
arr2: Ankur,Akash
arr2 length: 2




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.