DEV Community

Shahid Alam
Shahid Alam

Posted on

What is a class in JavaScript?

Stuck in tutorial hell

You may have come across this word "classes" which is often referred as a blueprint of different objects. we can create "instances" of it using the new keyword. but sometimes you don't really get what exactly is class even after reading several articles and getting trapped in tutorial hell.

Fret not. i'll try to explain it as easy as possible.

image

Think of classes as a stamp, like above.

Imagine you have to sign some documents for verification.
Now imagine there are 400 pages of documents on which your signature is needed(400 similar objects are needed). It'll take a lot of time if you do them one by one(keep declaring new objects with similar properties).

So, what do you do to save time and effort? You use a stamp(class) which will already have your name(object properties/functions/values) on it. Now you can simply use the stamp to validate different documents(create objects with same properties) much faster.

in code we do:

class Sign(){ // creating a class / stamp
      constructor(signature){ // engraving your signature on the stamp
            this.sign = signature; // assigning the signature to a property this.sign which will hold the value

                            }
         get thesign(){
            return this.sign
         }

}


const mySign = new Sign("cj")
console.log(mySign.sign) // cj
console.log(mySign.thesign) // cj
Enter fullscreen mode Exit fullscreen mode

Conclusion

I've tried my best to explain classes in JavaScript. If you find anything that's incorrect, please let me know. Thank you for reading!

Latest comments (0)