What is the difference between Object Properties and Object Methods?

What is the difference between Object Properties and Object Methods?
0.0 0

#1

Am I correct in saying that object properties are something about the object, like .length, and object methods are something you can do with the object, ie: .slice(). Is this always true? For example, .endsWith() is a method, but it sounds more like a property; you’re checking if the last character of a string matches the character provided as an argument - you’re not doing anything to the actual object.

Sorry for the newb question!


#2

your question is a good one.
In traditional OOP explanations, a property is a noun and a method is a verb.
But that is not always the case as you noted. Sometimes it can be a question like ‘endsWith()’

My own way of thinking about it is:
Anything that defines a behaviour is a function.
Anything that defines an attribute or characteristic that doesn’t require computation is a property.

I’m glad to say this is one of the topics that you get the hang of the more you code. So even if you’re a little unsure now, once you’re into OOP more, you will be a lot more confident about when to use a method and when to use a property.


#3

This makes sense. Thank you so much for the quick reply!


#4

They’re both properties on an object, methods are just properties that have a function as a value, and you need to execute the function to get it. Like the difference between:

var example = {
   foo: 1
}

And

var example = {
  foo: function() { return 1; }
};

You get the same value for both of those, but you have to execute the second one like example.foo(). Sometimes you just need a value, but sometimes you need to do some computation to actually get a value, as @hbar1st says.