I have the following JavaScript code. I have initialised an array using the new keyword, and therefore creating a new instance of the array object. I then populate the array by adding elements to it.
However I think I have made a fundamental misunderstanding - it is the next part of the code that has massively confused me, please correct my terminology if it is not clear enough or it is just plain wrong. I have logged (beatles.length). I am using the length property to find out how many elements are in the array. But why is it that length is a property and not a method?
Is it not the case that length is actually a method that the Array object can invoke that returns a numeric value? If length is not a method then why is it a property (a variable belonging to the array object)? Please explain the distinction here in a succinct way.
var beatles = new Array();
beatles[0] = "John";
beatles[1] = "Paul";
beatles[2] = "George";
beatles[3] = "Ringo";
console.log(beatles.length);
It is a property that gets increased or decreased as you push elements to the array object.
For example my (fake) object:
var myArray = function(){
this.length = 0;
this.push = function(itm){
this.length++;
// ^ doesn't do anything aside from increase length
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With