Course contentsShow
← JavaScript
Lesson 594 of 2,72315. ObjectsFree lesson

Methods in Object Literals

Define functions as properties to create methods on objects.

Methods in Object Literals

You'll learn how to add behavior to objects by defining functions as properties, creating reusable methods.

What Are Methods?

Up until now, you've stored data in object properties — numbers, strings, arrays, even other objects. But properties can hold functions too. When you store a function as a property of an object, we call it a method. Methods let your objects do things, not just hold things.

Think of an object like a toolbox. Properties are the tools inside (hammer, screwdriver), while methods are the actions you can perform (open the lid, close the lid).

Creating Methods

You define a method exactly like any other property — the value just happens to be a function:

const calculator = {
  brand: 'MathPro',
  add: function(a, b) {
    return a + b;
  },
  subtract: function(x, y) {
    return x - y;
  }
};

console.log(calculator.add(5, 3));        // 8
console.log(calculator.subtract(10, 4));  // 6

Notice how add and subtract are properties, but their values are functions. You call them using dot notation, just like accessing regular properties, but you add parentheses with arguments.

Why Use Methods?

Methods keep related behavior bundled with the data it operates on. Instead of scattered functions, you have organized objects that contain both state (properties) and behavior (methods):

const user = {
  name: 'Alice',
  age: 28,
  greet: function() {
    return 'Hello!';
  }
};

console.log(user.greet());  // "Hello!"

Key Takeaway: Methods are functions stored as object properties, allowing objects to have behavior alongside their data. Define them like any property, but with a function value.