CodeBlanks Logo Icon CodeBlanks

Object methods

Learn to define methods inside an object.

Object methods

When a property of an object is a function, it is called a method. In an object literal you can define methods with the shorthand: { greet() { return 'merhaba'; } }. This is the same as greet: function () { ... }.

Inside a method, the this keyword refers to the object itself. This lets you reach other properties with this.name. Example: const user = { name: 'Ayşe', greet() { return 'Merhaba ' + this.name; } }.

Call the method with a dot: user.greet(). Without parentheses you only get the function itself; to run it you need the parentheses.

Object.keys, values, entries

JavaScript provides three helpers to list an object's properties: Object.keys, Object.values and Object.entries. They live on the Object built-in, not on the object itself.

Object.keys(user) returns the property names as an array. Object.values(user) returns the values. Object.entries(user) returns an array of [name, value] pairs.

Example: Object.keys({ a: 1, b: 2 }) returns ['a', 'b']. These helpers are useful for loops and lookups.

Practice Calculator object

Define an object named calc. Its value property is 10. Its double() method returns this.value * 2. Call the method and print the result with console.log.

Starter code

index.js
// Define calc, call double() and print the result

Sample solution

index.js
const calc = { value: 10, double() { return this.value * 2; } };
console.log(calc.double());

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this refer to inside a method?

  • The global object
  • The function itself
  • A new object
  • The object the method belongs to Correct answer

Explanation: this refers to the object the method was called on.

2 Reach with this

Question
const user = { name: 'Ayşe', greet() { return 'Merhaba ' + this.____; } };
Answer
const user = { name: 'Ayşe', greet() { return 'Merhaba ' + this.name; } };

Explanation: this.name reads the name property of user.

3 Match the Object helpers

Term Meaning
Object.keys(o) Names array
Object.values(o) Values array
Object.entries(o) Name-value pairs
o.method() Method call

All lessons in Beginner