Learn JavaScript: Arrays: length property


#1

Hi all, first post.

Just a quick question: why is it that when calling a string method, I have to use () at the end, but when calling the length method for an array I don’t? Compare the following:

let x = ‘hi’;
console.log( x.toUpperCase() );

let y = [1,2];
console.log( y.length );

Cheers,

Laurie


#2

toUpperCase is a method, length isn’t a method. Its a property.

The length property of an object which is an instance of type Array [source]


#3

Ah ok, so properties don’t need the brackets, because your not calling them like functions but like, well, properties?


#4

yes, lets say we make an object:

obj = {
  prop: 3,
  method(){
    return 5;
  }
}
console.log(obj.prop);
console.log(obj.method())

we clearly see the property doesn’t have parentheses, while the method does. Methods are just functions inside object or class. Now, Array has a bit more properties and methods, but this gives the general idea.


#5

Perfect, thank you! I understand now, very clear explanation.


#6

Well, i took a few shortcuts in my explanation.

This might be even better:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

// create instance of Car
var mycar = new Car('Eagle', 'Talon TSi', 1993);

Given creating an array creates instance of Array type (“automatically”).

And just like many pieces of software, programming languages have updates. the latest version (es6, which you are learning), also introduced classes (es5 only had objects). Which makes things very confusing.