Property vs Method

What is the difference between a property and a method in JavaScript?

JavaScript has objects. Objects are made up of key value pairs. The keys are the properties and the values can be anything. So a method could be the value of a key. Properties are just like variables but they belong to an object.

In general use (at least in my experience) and as a general rule people will call something a property on an object if the key’s value isn’t a method.

In ES5 the above explanation covers it. Properties can be values or methods. ES6+ changes the landscape a bit by writing methods similar to typical function syntax (but without the keyword).

ES5

obj = {
    prop1: value,
    method1: function () {
        // code
    }
}

ES6+

obj = {
    prop1: value,
    method1 () {
        //
    }
}

Both methods are still called on their owner object in the same manner,

obj.method1()

The general idea of embedding methods in objects is to give context (the owner object) so its properties can be accessed with this.

    return this.prop1;

If context is not needed, then the method can be written as a freestanding function in whatever scope it will apply, outside of the object. This will make it universally available to the program. Methods are only available to their owner object.

1 Like

While the syntax that you can use changes in ES6, it is syntactic sugar the under the hood it is the same. It is the same as classes in ES6, all just syntactic sugar nothing under the hood has changed. It’s just there to make the programmer’s job easier.