Menu
Coddy logo textTech

Adding Methods to Objects

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 2 of 56.

Objects in JavaScript can contain not only data properties but also methods - functions that belong to the object.

Create a simple object with a property:

const person = {
  name: "John"
};

Add a method to the object:

const person = {
  name: "John",
  greet: function() {
    return "Hello!";
  }
};

Call the method:

person.greet(); // Returns "Hello!"

You can also use the shorthand syntax introduced in ES6:

const person = {
  name: "John",
  greet() {
    return "Hello!";
  }
};
challenge icon

Challenge

Add an add method to the calculator object that takes two numbers and returns their sum.

Example usage:

calculator.add(5, 3); <i>// returns 8</i>

Cheat sheet

Objects in JavaScript can contain methods - functions that belong to the object.

Add a method to an object:

const person = {
  name: "John",
  greet: function() {
    return "Hello!";
  }
};

Call the method:

person.greet(); // Returns "Hello!"

ES6 shorthand syntax for methods:

const person = {
  name: "John",
  greet() {
    return "Hello!";
  }
};

Try it yourself

let a = parseInt(inp[0]); // Don't change this line
let b = parseInt(inp[1]); // Don't change this line

// The calculator object already exists 
const calculator = {
  // TODO: Add the 'add' method here that takes two numbers and returns their sum

};

console.log(calculator.add(a, b));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming