Skip to content

JavaScript static keyword | Basic code

  • by

JavaScript static keyword is used to define 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. In order 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 make use of 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

Do 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 *