Access the length of an array in JavaScript

Description

The number of items in an array is stored in the length property.

Example

The following code shows how to access the length of an array.


//creates an array with three strings
var colors = [ "A", "B", "C" ];
//creates an empty array
var names = [];
console.log(colors.length); //3
console.log("<br/>");
console.log(names.length); //0
// w ww .  jav  a2  s  . c  o  m

The code above generates the following result.

length is not read-only

By setting the length property, you can remove or add items to the end of the array.


//creates an array with three strings 
var colors = ["A", "B", "C"]; 
colors.length = 2; //from   w  w  w .ja v  a 2  s. com
console.log(colors[2]);  //Undefined 

//add a color (position 99) 
colors[99] = "D";
console.log(colors.length); //100 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window