JS Array Length

Every array in javascript has array.length element which will get the array length.

Following array has a length of 5:

var arr = new Array(1,2,3,4,5);
alert(arr.length); // 5 

Array which is empty has a length of 0:

var arr = new Array();
alert(arr.length); // 0 

There is no size limit for an array. You can define an array as large as you can if your computer can support.

If an index of array is out of the range, it's value is undefined:

var arr = new Array(1,2,3,4,5);
alert(arr[7]); // undefined 

To use an arry safely:

var arr = new Array(1,2,3,4,5);
var sum = 0;
for (var i=0; i<arr.length; i++)
	sum += arr[i];
alert(sum); // 15 

Set array size with values as "undefined":

var arr = [];
arr.length = 2;
for (var i = 0; i<arr.length; i++)
	alert(arr[i]); //undefined

endmemo.com © 2024  | Terms of Use | Privacy | Home