JavaScript class methods are functions defined inside a class that describe the actions an object can perform. They allow you to organize reusable behavior alongside the properties of an object.
For example, a Student class can contain methods to display student details, calculate marks, or check whether a student has passed an examination.
Class methods were introduced as part of the ES6 class syntax in ECMAScript 2015. They make it easier to write structured JavaScript code and work with objects.
In this tutorial, you will learn how to define class methods, call methods using objects, pass arguments, return values, use the this keyword, and understand different types of methods.
What Are Methods in JavaScript Classes?
A method is a function defined inside a class. It describes an operation that an instance of the class can perform.
Consider a class that represents a person. It can store the person’s name and provide a method to display a greeting.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
const person1 = new Person("Rahul");
person1.greet();
Output:
Hello, Rahul!
In this example:
class Persondefines the class.constructor(name)initializes the person’s name.greet()defines a class method.person1.greet()calls the method on the object.
The method uses this.name to access the name stored in the current instance.
If you need a refresher on creating objects and their properties, read JavaScript Objects.
How to Define Methods in JavaScript Classes
You can define a method inside a class by writing its name, parentheses, and a block of code. Unlike a traditional function expression, you do not need to write the function keyword.
Basic Method Syntax
class ClassName {
methodName() {
// Code to execute
}
}
Here, methodName is the name of the method. The code inside its curly braces runs when the method is called.
Example of a Class Method
class Message {
showMessage() {
console.log("Welcome to JavaScript!");
}
}
const message = new Message();
message.showMessage();
Output:
Welcome to JavaScript!
The showMessage() method displays a message when called through the message object.
Defining a method does not automatically execute its code. You must call it unless it is invoked by some other operation.
Calling Class Methods Using Objects
After creating an instance of a class, you can call its methods using dot notation.
The syntax is:
objectName.methodName();
Example
class Calculator {
add() {
console.log(10 + 20);
}
}
const calculator = new Calculator();
calculator.add();
Output:
30
Here, calculator is an instance of the Calculator class, and add() is the method called on that instance.
You can create multiple objects from the same class and call the same method on each object.
class User {
greet() {
console.log("Hello!");
}
}
const user1 = new User();
const user2 = new User();
user1.greet();
user2.greet();
Output:
Hello!
Hello!
Both objects can access the same class method. By default, ordinary instance methods are defined on the class prototype and shared by instances.
Methods with Parameters
Class methods can accept parameters just like regular functions. Parameters allow a method to work with different values whenever it is called.
Example
class Calculator {
add(a, b) {
console.log(a + b);
}
}
const calculator = new Calculator();
calculator.add(10, 20);
calculator.add(50, 30);
Output:
30
80
The add() method accepts two parameters, a and b. The values supplied when calling the method are used in the calculation.
This makes the method reusable without needing to define a separate method for every pair of numbers.
Passing Multiple Arguments
A method can accept as many parameters as your task requires.
class Employee {
displayDetails(name, role, salary) {
console.log(`Name: ${name}`);
console.log(`Role: ${role}`);
console.log(`Salary: ₹${salary}`);
}
}
const employee = new Employee();
employee.displayDetails("Priya", "Developer", 35000);
Output:
Name: Priya
Role: Developer
Salary: ₹35000
The method receives three arguments and displays their values. You can also initialize these values in the constructor if they belong to the employee object itself.
Methods with Return Values
A class method can return a value using the return statement. The returned value can be stored in a variable, printed, or used in another calculation.
Example
class Calculator {
multiply(a, b) {
return a * b;
}
}
const calculator = new Calculator();
const result = calculator.multiply(5, 4);
console.log(result);
Output:
20
The multiply() method returns the result instead of displaying it directly.
This makes the method more flexible because the calling code decides what to do with the returned value.
Using a Returned Value in Another Calculation
class Calculator {
add(a, b) {
return a + b;
}
}
const calculator = new Calculator();
const result = calculator.add(10, 20) * 2;
console.log(result);
Output:
60
The add() method returns 30, and the calling code multiplies that value by 2.
Remember that a method without an explicit return statement returns undefined by default.
Using the this Keyword in Class Methods
The this keyword allows a method to access properties and other methods associated with the current object.
When a method is called through an object, such as person.greet(), this normally refers to that object.
Example
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
displayDetails() {
console.log(`Name: ${this.name}`);
console.log(`Age: ${this.age}`);
}
}
const person1 = new Person("Rahul", 25);
const person2 = new Person("Ayesha", 22);
person1.displayDetails();
person2.displayDetails();
Output:
Name: Rahul
Age: 25
Name: Ayesha
Age: 22
The same method displays different details because this refers to the instance through which the method is called.
Calling One Method from Another Method
A class method can call another method using this.
class Student {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
displayName() {
console.log(`Student: ${this.getName()}`);
}
}
const student = new Student("Priya");
student.displayName();
Output:
Student: Priya
The displayName() method calls getName() through this and displays the returned name.
Important: If you extract a class method and call it without its object, its this value is not automatically bound to the original instance. You can use bind() when you need to preserve that context.
Using Default Parameters in Class Methods
Class methods support default parameters. These values are used when the corresponding argument is missing or explicitly passed as undefined.
class Greeting {
greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
}
const greeting = new Greeting();
greeting.greet("Rahul");
greeting.greet();
Output:
Hello, Rahul!
Hello, Guest!
The first call uses the supplied name, while the second call uses the default value.
You can learn more about this feature in JavaScript Default Parameters.
Different Types of Class Methods
JavaScript classes support several kinds of methods. The most common ones include instance methods, static methods, getters, and setters.
Instance Methods
Instance methods are ordinary class methods that are usually called through an object created from the class.
class Car {
start() {
console.log("The car has started.");
}
}
const car = new Car();
car.start();
Output:
The car has started.
The start() method is an instance method because it is called through the car object.
Static Methods
Static methods belong to the class itself rather than to individual instances. You define them using the static keyword.
class MathHelper {
static square(number) {
return number * number;
}
}
console.log(MathHelper.square(5));
Output:
25
The square() method is called directly through MathHelper.
You generally cannot call it as new MathHelper().square(5) because static methods are not available as ordinary instance methods.
Getters and Setters
Getters and setters allow you to define behavior for reading and assigning a property.
class Product {
constructor(price) {
this._price = price;
}
get price() {
return this._price;
}
set price(value) {
if (value >= 0) {
this._price = value;
}
}
}
const product = new Product(1000);
console.log(product.price);
product.price = 1500;
console.log(product.price);
Output:
1000
1500
The getter runs when you read product.price, and the setter runs when you assign a new value to it.
The example uses _price as an internal naming convention. The underscore itself does not make a property private.
Class Methods vs Regular Functions
Class methods and regular functions can both perform operations, but they are defined and used differently.
| Feature | Class Method | Regular Function |
|---|---|---|
| Definition | Inside a class body | Can be declared or assigned in different scopes |
| Calling | Usually through an instance or class | Through its function name or reference |
this behavior | Depends on how the method is called | Depends on how the function is called, unless bound |
| Common purpose | Organizing behavior related to a class | General-purpose reusable operations |
Example of a regular function:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Rahul"));
Output:
Hello, Rahul!
Example of a class method:
class Greeting {
greet(name) {
return `Hello, ${name}!`;
}
}
const greeting = new Greeting();
console.log(greeting.greet("Rahul"));
Output:
Hello, Rahul!
Both examples return the same result, but the class method is organized within a class.
Common Mistakes with JavaScript Class Methods
Calling a Method Without Parentheses
When you write object.method without parentheses, you access the method function rather than execute it.
class Message {
show() {
return "Hello!";
}
}
const message = new Message();
console.log(message.show);
console.log(message.show());
The first statement displays a function reference, whose exact representation varies by environment. The second calls the method and returns "Hello!".
Using this Incorrectly
The this keyword does not always refer to the object where a method was originally defined. It depends on how the method is called.
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const user = new User("Rahul");
console.log(user.greet());
Output:
Hello, Rahul!
Calling user.greet() gives the method the correct object context.
Forgetting to Return a Value
If you want to use a method’s result elsewhere, make sure it returns a value.
class Calculator {
add(a, b) {
return a + b;
}
}
const calculator = new Calculator();
const result = calculator.add(5, 10);
console.log(result);
Output:
15
Without return, the method would return undefined unless it explicitly returned something else.
Frequently Asked Questions
What is a method in JavaScript?
A method is a function associated with an object or class. It defines an action that can be performed using that object or class.
How do you call a class method?
Create an instance using new, then call the method with dot notation, such as object.method().
Can class methods accept parameters?
Yes. Class methods can accept parameters, use default values, and return results just like other functions.
What is the difference between an instance method and a static method?
An instance method is generally called through an object, while a static method is called through the class itself.
Can one class method call another?
Yes. You can call another instance method using this.methodName() when the current this value refers to the intended instance.
Do class methods get copied into every object?
Ordinary class instance methods are typically stored on the class prototype and shared by instances rather than being copied as own properties onto every object.
Conclusion
JavaScript class methods allow you to organize reusable behavior inside classes. You can define methods to display information, perform calculations, update object data, and return results.
By understanding parameters, return values, the this keyword, static methods, getters, and setters, you can use class methods effectively in modern JavaScript applications.