I found that both the Array
Object and Array.prototype
have the length
property. I am confused on using the Array.length
property. How do you use it?
Console.log(Object.getOwnpropertyNames(Array));//As per Internet Explorer
outputs:
length,arguments,caller,prototype,isArray,
Prototype
and isArray
is usable but how do you use the length
property?
Array
is a constructor function.
All functions have a length
property that returns the number of declared parameters in the function definition.
Array.length
is how many arguments the function Array()
takes and Array.prototype.length
is an instance method that gives you the length of your array. When you check ['foo'].length
you're actually checking Array.prototype.length
with the this
argument being your array ['foo']
var myArray = ['a','b','c']
console.log(myArray.length); //logs 3
If you have an instance of an Array
, it inherits all properties from the Array.prototype
thanks to Javascript's use of prototypical inheritance.
Take the following example:
function MyClass() {
this.foo = Math.random();
}
MyClass.prototype.getFoo = function() {
return this.foo;
}
// Get and log
var bar = new MyClass();
console.log(bar.getFoo());
This declares a function (serving as the constructor) for a class. That function provides the prototype for each instance of the class. When we assign a method (getFoo
) to that prototype, every instance of the class will have the method.
You can then call the method on an instance and it will be applied to the data that class contains. In the case of arrays, the length
property will get the length of the array you call it on:
[1, 2, 3, 4].length == 4; // Every array has a length
However, because functions behave largely like objects and may have their own properties, Array
itself may have properties. That is what you see when using Array.length
, which gets the number of parameters the Array
(constructor) function expects to receive. Every function has a length
property.
Array.length
provides the number of declared parameters in Array
function definition. Since Array function definition has only one size
parameter, hence it will return 1 irrespective of your array content.
Array.prototype.length
provides the number of elements in array data. It is dependent on the array content.
var arr=new Array();
console.log(Array.length);//returns 1
console.log(arr.length);//returns 0 as array has 0 elements