Methods: Functions Inside Objects

Grade 8, page 5 of 13. A one-minute read.

Remember that functions are values (Grade 6)? That means a property's value can be a function. When a function lives inside an object, it's called a method:

JavaScript
const robot = {
  name: "Robo-Chef",
  greet: function () {
    console.log("Beep boop! How may I serve you? 🤖");
  },
  makeSandwich() {
    console.log("Placing entire bag of bread on plate... 🍞");
  },
};

robot.greet();
robot.makeSandwich();

It prints

Beep boop! How may I serve you? 🤖
Placing entire bag of bread on plate... 🍞

Both ways of writing a method work, but the second one (makeSandwich() { ... }) is a modern shortcut called method shorthand, and it's what most people use today.

And now you understand console.log() completely: console is an object, and log is a method on it. When you call console.log("hi"), you're calling the log method of the console object. 🤯

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning