Class method

2 snippets in JavaScript

JSJavaScript

Class Declaration

JS · Classes & OOP
Syntax
class ClassName {
  constructor(params) { ... }
  method() { ... }
}
Example
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  format() {
    return `${this.name}: $${this.price.toFixed(2)}`;
  }
}

const item = new Product("Notebook", 12.5);
console.log(item.format());
Output
"Notebook: $12.50"

Note Classes are syntactic sugar over prototypes. They are NOT hoisted -- you must declare before use, unlike function declarations.

Static Methods and Properties

JS · Classes & OOP
Syntax
class C {
  static method() { ... }
  static property = value;
}
Example
class MathUtils {
  static PI = 3.14159265;

  static clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }

  static lerp(a, b, t) {
    return a + (b - a) * t;
  }
}

console.log(MathUtils.clamp(150, 0, 100)); // 100
console.log(MathUtils.lerp(0, 50, 0.5));  // 25

Note Static members belong to the class itself, not instances. Access them via ClassName.method(), not instance.method().

Frequently asked questions

How does JavaScript handle class method?
JavaScript covers this with 2 copy-ready snippets on this page. The "Class Declaration" snippet in JavaScript uses `class ClassName {`.
Which code does the JavaScript example use?
The "Class Declaration" snippet uses `class ClassName {`, from the Classes & OOP section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "class method"?
Besides "Class Declaration", this page also shows "Static Methods and Properties".
Is there anything to watch out for?
Yes. For "Class Declaration": Classes are syntactic sugar over prototypes. They are NOT hoisted -- you must declare before use, unlike function declarations.