DEV Community

Cover image for static in JavaScript
Rahul
Rahul

Posted on

3 1

static in JavaScript

This keyword static allows us to create methods and properties that are assigned to the class itself, and not it's instances.

class person {
    // A static method
    statis hello() {
        console.log("Hello!");
    }
}

// Call the static method directly
Person.hello();
Enter fullscreen mode Exit fullscreen mode

Value of "THIS"

Inside statis methods, "this" hold a reference to the class.

class Test {
    statis getThisValue() {
         console.log(thos);
    }
}

// Call the static method
Test.getThisVkaue();

/* 
  class Test { ... }
*/ 
Enter fullscreen mode Exit fullscreen mode

EXAMPLE 1

class Car {
    constructor(make, model) {
         this.make = make; 
         this.make = model; 
    }
    // This statis method creates a new instance of Car
    static createCar(make, mmodel) {
        console.log("Building a new car...");

        return new this(make, model);
    }

    info() {
        console.log(`I'm a ${this.make} ${this.model})
    }
}

// Call the static method "createCar" directly from the car class

let bmw = Car.createCar("BMW", "E82");

// Run our "info" method from the Car instance

bmw.info();

/*
   Building a new car...

   I'm a BMW E82!

*/
Enter fullscreen mode Exit fullscreen mode

When should you use "STATIC"?

You shouuld use static methods and properties whenever,

  • You're writing utility classes that don't change
  • The method should not be changes or overridden
  • The code is not dependent on instance creation

Have anything in mind ? Comment Below!

⚡Thanks For Reading | Happy Coding 😁

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay