JAVASCRIPT

Methods in JavaScript

Adding a method in a class is like creating a regular function, except there's no need for the function keyword.

This VirtualPet class can't do much yet. Let's give it the ability to eat with a method.

 class VirtualPet {
 constructor(name) {
  this.name = name;
 }
 eat() {}
}

Inside the braces, methods work like normal functions.

Let's use console.log to display a message in the console when eat() is called.

class VirtualPet { 
 constructor(name) {
  this.name = name;
 }

 eat() {
  console.log("nom nom");
 }
}

To use the eat() method, we'll need the name of the object, a period, the name of the method, and parentheses.

class VirtualPet { 
 constructor(name) {
  this.name = name;
 }

 eat() {
  console.log("nom nom");
 }
}

const pet = new VirtualPet("Tom");
pet.eat();
Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH