Home » Programming » Javascript » Javascript Array Length

How to Get the Length of an Array in JavaScript [Examples]

This article will show you how to get the length of an array in JavaScript, as well as provide some code examples.

JavaScript is one of the most popular programming languages. From humble origins as a webpage scripting language for animating menus and displaying pop-up ads, it is now a full-blown ecosystem that you can use to build cross-platform mobile apps, web pages, server processes, and even games.

JavaScript Arrays

Arrays are a vital building block for any program, even simple ones. An array is a container that holds any number of other values or objects. So it’s a list of things.

Each item stored in an array has an index which indicates that item’s position in the array. These indexes are numerical – counting starts at 0 for the first item in the array.

Array Example

Here’s an array containing some trees:

var trees = ['pine', 'birch', 'spruce'];

pine is the first item in the array, at index 0birch is the second item in the array at index 1, and so on.

The length Property of Arrays

To find the length (number of items in) an array, simply use the length property of the array:

trees.length //Returns 3

Simply access the length property of your array variable, and the number of items will be returned as an integer value.

Truncating / Setting the Length

The length property has one other trick up its sleeve – it can be used to set the length of an array as well as reading it.

This will cut off all items in the array past the given length:

trees.length = 2;
console.log(trees) // ['pine', 'birch']
trees.length; // Now returns 2

Above, the length property of the trees array is set to 2. As it was previously 3, the last item in the array (the spruce value) is deleted to make the array the given length of 2.

When the length property is reaccessed, it now reads the new value of 2.

Check out these other useful things you can do with JavaScript arrays:

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment