Skip to content

JavaScript static keyword | Basic code

  • by

The JavaScript static keyword defines a static method or property for a class, or a class static initialization block. The static methods and properties can be called directly from the class. They don’t need class instances.

static methodName() { /* ... */ }
static propertyName [= value];

// Class static initialization block
static {

}

The static keyword can be accessed on the class definition only. To access the static keyword for non-static methods, one needs to invoke them using the class name. However, for calling a static method within another static method, we can use this keyword.

JavaScript static keyword

Simple example code implementation of using static keyword within a class:

<!DOCTYPE html>
<html>
<body>
  <script>    
   class A {  

    static displayName = "StaticName";

    static staticHello() {  
      return "Calling Static method.";  
    }  
  }  

  console.log(A.displayName);
  console.log(A.staticHello)
  console.log(A.staticHello())
</script>  

</body>
</html>

Output:

JavaScript static keyword

Take a look at another example:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  static displayName = "StaticName";
  static print(){
    return "Static method print() is called from Rectangle";
  }
}

console.log(Rectangle.displayName); // "StaticName"
console.log(Rectangle.print()); // "Static method print() is called from Rectangle"

Calling static property from a class instance will return undefined:

let rec = new Rectangle(2, 3);

console.log(rec.displayName); // undefined
console.log(rec.print()); // rec.print is not a function

Static Method:

class MyClass {
  // Static method
  static myStaticMethod() {
    console.log('This is a static method.');
  }
}

// Calling the static method
MyClass.myStaticMethod();

In this example, myStaticMethod is a method of the class MyClass, and you can call it without creating an instance of MyClass.

Static Property:

class MyClass {
  // Static property
  static myStaticProperty = 'This is a static property.';
}

// Accessing the static property
console.log(MyClass.myStaticProperty);

Static properties are also accessed using the class name, and they are shared among all instances of the class.

Comment if you have any doubts or suggestions on this JS static tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *