Monday, July 22, 2013

JavaScript: Length of Arrays

JavaScript arrays are dynamic and flexible with a few gotcha's. Today we will have an in-depth look at the length property, which is an unsigned 32 bit integer that specifies the number of elements in an array. Arrays have 0 based indices, therefore the length property will be the highest index + 1. Lets have a look at some examples

var a = [];

a.length   //return 0, a is an empty array

var b = [2,4,6];

b.length   //return 3

b[3] = 8;

b.length   //returns 4

b['a'] = 5;   //never a good idea to use an array as an associative array, instead use a plain object

b.length   //returns 4, non numeric indices are ignored in the length property

b[10000] = 50;

b.length   //returns 10001, the positions between 3 and 10000 are padded with undefined

Setting the length of an array will shorten it as well

b.length = 4

b.length   //returns 4, shortened the array from 10001 to 4

The safest way to empty an array is to set the length to 0

b.length = 0;   //empty's an array

Next, I will be looking at the slice and splice functions on an array, till next time.......

No comments: