Mark As Completed Discussion

Object methods are functions that are defined as properties of an object. They allow us to perform actions or calculations using the object's properties or other data.

In JavaScript, object methods are defined by assigning a function to a property of the object. The function can then be called using dot notation and parentheses.

For example, let's say we have an object person with properties name and age. We can define a method called greet that logs a greeting message using the person's name:

JAVASCRIPT
1const person = {
2  name: 'John',
3  age: 25,
4  greet: function() {
5    console.log('Hello, my name is ' + this.name);
6  }
7};
8
9person.greet();

In this example, the greet method is defined as a function that logs a greeting message using the name property of the person object.

When calling a method, the this keyword refers to the object itself. In the greet method, this.name refers to the name property of the person object.

You can define multiple methods for an object, each performing different actions or calculations. Methods can also accept parameters and return values, just like regular functions.

Try running the code example to see the output.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment