In JavaScript, Static Methods are associated with a class rather than an instance of the class.
They are defined using the static keyword within a class and are called on the class itself, not on instances of the class.
Static methods are useful for operations that don't depend on the state of an instance and are common across all instances of the class.
class MathOperations { // Static method for multiply static multiply(num1, num2) { return num1 * num2; } // Static method for divide static divide(num1, num2) { return num1 / num2; } } // Calling static methods on the class itself console.log(MathOperations.multiply(10, 2)); // Outputs: 20 console.log(MathOperations.divide(10, 5)); // Outputs: 2
multiply and divide are static methods of the MathOperations class.
They don't require an instance of the class to be created, and you can call them directly on the class.
Defined with static Keyword: Static methods are defined using the static keyword within a class.
Accessed on the Class: They are called on the class itself, not on instances of the class. For example, MathOperations.multiply(10, 2).
No Access to Instance Properties: Static methods cannot access instance properties or methods because they are not called on an instance.
class DateUtils { // Static method to check if a year is a leap year static isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0); } } // Calling the static method on the class console.log(DateUtils.isLeapYear(2024)); // Outputs: true console.log(DateUtils.isLeapYear(2017)); // Outputs: false
the "isLeapYear" method is a static method that checks if a given year is a leap year.
It can be called on the "DateUtils" class without creating an instance.