Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the JavaScript Array.length property a function or a simple variable?

Tags:

javascript

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);
like image 573
user1554264 Avatar asked Jul 18 '26 15:07

user1554264


1 Answers

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
   };
};
like image 128
Naftali Avatar answered Jul 21 '26 04:07

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!