JavaScript

Using Static Keyword in JavaScript

Cory Rylan

- 1 minute

This post, we will learn how the static keyword works in JavaScript. First, let's take a look at a simple JavaScript Class.

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

greet() {
console.log(`Hello, ${this.firstName} ${this.lastName}`);
}
}

const person = new Person('Cory', 'Rylan');
person.greet(); // Hello, Cory Rylan

const person = new Person('John', 'Doe');
person.greet(); // Hello, John Doe

With JavaScript Classes, we can add methods and properties that can be accessed per instance of the Class. This is standard behavior when you make multiple instances of a Class. If we create a method that does not access an instance property, we can use the static keyword.

class MathUtils {
static add(num, num2) {
return num + num2;
}

static subtract(num, num2) {
return num - num2;
}
}

// Static Methods
console.log(MathUtils.add(1, 2)); // 3

// Cannot access static values on instance
const instance = new MathUtils();
instance.add(); // error undefined

When creating a static method, it can only be accessed on the Class definition itself. If you try to access the method on an instance, it will fail. Static methods are useful for utility methods that do not contain any state. One could argue that if you have static methods, you could refactor them to be plain functions instead.

You can also use the static keyword on properties and getters.

class MathUtils {
static value = '';
}

// Static Properties
MathUtils.value = 'Hello from static property';
console.log(MathUtils.value);

When using static properties, you can access them and set them any time, but they exist only on the Class itself and are not accessible to any instance of the Class. Along with static properties, you can create static getters.

class MathUtils {
static get random() {
return Math.random();
}
}

// Static Getter
console.log(MathUtils.random, MathUtils.random); // two different values

Static getters allow you to compute values on the fly with a property. For this example, we return a new value anytime we access the random property. Check out the full working demo below!

View Demo Code   
 

No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

JavaScript

Use JavaScript Date Objects with the HTML5 Date Picker

Learn how to easily use both the native HTML5 datepicker and JavaScript Date objects together.

Read Article
Web Performance

Design System Performance with Clarity Core Web Components

Learn how to build high performance UI and Design Systems on the Web using Clarity Core.

Read Article
Web Components

State of Web Components in 2020

Learn a brief overview on Web Components and the latest tech available to build and distribute components across the Web.

Read Article