Wednesday, January 1, 2014

The JavaScript length Property

The length property in JavaScript is used to determine how many elements are in a thing. I use the word thing because the length property can be used on almost any kind of variable.

The standard way to use the length property is with a String or Array. When used thusly,

var i = myString.length;

The result of i will the the number of characters in myString

var b = myArray.length;

The result of b will be the number of elements in myArray

I use the length property all the time when iterating over an array

var myArray = [1, 2, 3, 4];
for(var i = 0; i < myArray.length; i += 1) {
console.log(myArray[i]);
}

In the JavaScript console, this can be seen

1234

No comments:

Post a Comment