0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Method in JavaScript Class: Simple Guide

In JavaScript, you create a method inside a class by defining a function directly within the class body using methodName() { } syntax. This method can then be called on instances of the class using instance.methodName().
📐

Syntax

A method in a JavaScript class is defined by writing the method name followed by parentheses and curly braces inside the class body. It looks like a function but without the function keyword.

  • class: keyword to declare a class.
  • methodName(): the name of the method followed by parentheses.
  • { }: curly braces contain the code the method runs.
javascript
class MyClass {
  methodName() {
    // code to run
  }
}
💻

Example

This example shows a class Car with a method startEngine. When called, it prints a message to the console.

javascript
class Car {
  startEngine() {
    console.log('Engine started');
  }
}

const myCar = new Car();
myCar.startEngine();
Output
Engine started
⚠️

Common Pitfalls

Common mistakes include:

  • Using the function keyword inside a class method (not needed).
  • Forgetting to create an instance before calling the method.
  • Calling the method without parentheses, which returns the function itself instead of running it.
javascript
/* Wrong: Using function keyword inside class */
class WrongClass {
  sayHi() {
    console.log('Hi');
  }
}

/* Right: Method without function keyword */
class RightClass {
  sayHi() {
    console.log('Hi');
  }
}

const obj = new RightClass();
obj.sayHi(); // Correct way to call method
Output
Hi
📊

Quick Reference

Remember these points when creating methods in JavaScript classes:

  • Define methods without the function keyword.
  • Call methods on instances, not on the class itself.
  • Use parentheses () to invoke methods.

Key Takeaways

Define methods inside classes using methodName() { } syntax without the function keyword.
Create an instance of the class before calling its methods.
Always use parentheses to call a method, like instance.methodName().
Class methods are like functions tied to objects created from the class.
Avoid syntax errors by not using the function keyword inside class method definitions.