Home » JavaScript

Array length property with example in JavaScript

JavaScript array length property: Here, we are going to learn about the length property of array in JavaScript.
Submitted by IncludeHelp, on February 27, 2019

JavaScript length property

length property is used to get and set the length of an array in JavaScript.

Syntax to get the length of an array:

    array_name.length;

Syntax to set the length of an array:

    array_name.length = value;
    //Here, value is the total number elements 
    //(length) to set to an array.

Examples:

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

    Function call:
    arr1.length;
    
    Output:
    5

JavaScript Code to get/set the length of an array

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

<body>
	<script>
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = ["Amit", "Ankur", "Akash"];
		var arr3 = [];
		
		//getting length
		document.write("length of arr1: " + arr1.length + "<br>");
		document.write("length of arr2: " + arr2.length + "<br>");
		document.write("length of arr3: " + arr3.length + "<br>");
		
		//setting a length
		arr3.length = 10;
		document.write("length of arr3: " + arr3.length + "<br>");
	</script>
</body>
</html>

Output

length of arr1: 5
length of arr2: 3
length of arr3: 0
length of arr3: 10





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.