JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to find the length of an array in JavaScript?

In this tutorial, you will learn how to find the number of elements in an array. You know that an array is a variable that holds multiple values. But actually, the array is an object, and it has various methods and properties. One such property is length.

Every array has a length property that returns the number of elements present in that array.

let arr = [7, 14, 21, 28, 35];
console.log(arr.length); //5

let indoorGames = Array.of('Chess', 'Table Tennis', 'Scrabble');
console.log(indoorGames.length); //3

One important thing about the length property that you must be aware of is that you can assign a numeric value to the length property. When you assign a number greater than the array's length to the length property, new elements are added to the array with an undefined value. But when you assign a number smaller than the array's length, the array is truncated.

let arr = [7, 14, 21, 28, 35];
console.log(arr.length); //5

arr.length=7;
console.log(arr); //[7, 14, 21, 28, 35, undefined, undefined]

arr.length = 3;
console.log(arr); //[7, 14, 21]

Recommended Posts