In JavaScript, you can also define class methods like in other programming languages.
Generally, these methods are bound to a class, not the instances of the class i.e they are called on the class itself, instead of the instances (or objects) of the class.
The keyword static is used in a JavaScript class to define static class methods.
To illustrate a practical example, I would like to share a code snippet that involves TypeScript and API calls using axios
. The file name is api.ts
.
import axios, { AxiosResponse } from 'axios';
import { Insurer } from '@models/insurer';
export default class Api {
static getInsurers = async (): Promise<AxiosResponse<Insurer[]>> => {
return await axios.get('/api/v1/insurers');
};
}
We import class Api and call our static method on the class level.
import { AxiosResponse } from 'axios';
import { Insurer } from '@models/insurer';
import Api from './api';
const response: AxiosResponse<Insurer[]> = Api.getInsurers();
As you can see we don't instantiate an object of class Api, and even if you do and call a static method on that object it will raise an error.
Conclusion
Static class methods are like helper or utility methods that are not dependent on the instances; they are bound to the class. The concept is the same in all programming languages including JavaScript.