0
0
Javascriptprogramming~5 mins

Array length property in Javascript

Choose your learning style9 modes available
Introduction

The array length property tells you how many items are in the array. It helps you know the size of the list you are working with.

When you want to count how many elements are in a list of items.
When you need to loop through all items in an array.
When you want to add or remove items and check the new size.
When you want to check if an array is empty or not.
When you want to limit actions based on the number of elements.
Syntax
Javascript
const array = ['item1', 'item2', 'item3'];
const size = array.length;

The length property is always one more than the highest index because arrays start at 0.

You can read length to get the number of items, or set it to change the array size.

Examples
Outputs 3 because there are three items in the array.
Javascript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length);
Outputs 0 because the array has no items.
Javascript
const emptyArray = [];
console.log(emptyArray.length);
Outputs 1 because there is exactly one item.
Javascript
const oneItem = ['only'];
console.log(oneItem.length);
Setting length to 2 cuts the array to first two items: [10, 20].
Javascript
const numbers = [10, 20, 30, 40];
numbers.length = 2;
console.log(numbers);
Sample Program

This program shows how to get the length of an array, use it to loop through all items, and then change the length to remove items.

Javascript
const colors = ['red', 'green', 'blue', 'yellow'];
console.log('Original array:', colors);
console.log('Length:', colors.length);

// Loop through the array using length
for (let index = 0; index < colors.length; index++) {
  console.log(`Color at index ${index}:`, colors[index]);
}

// Change length to remove last two colors
colors.length = 2;
console.log('Array after changing length:', colors);
console.log('New length:', colors.length);
OutputSuccess
Important Notes

Accessing length is very fast, O(1) time complexity.

Changing length to a smaller number removes items from the end, which frees memory.

Common mistake: expecting length to count only non-empty or non-undefined items, but it counts all indexes.

Use length when you need to know or control the size of the array quickly.

Summary

The length property tells how many items are in an array.

You can read it to count items or set it to change the array size.

It is useful for loops, checks, and managing array size.