DEV Community

What are Classes and How to Use Them in JavaScript ? πŸ€”πŸ€”

Sandeep Nautiyal on April 24, 2024

JavaScript, prior to ES6 (ECMAScript 2015), relied on constructor functions to mimic object-oriented concepts. These functions act as blueprints fo...
Collapse
Β 
tracygjg profile image
Tracy Gilmore β€’

Hi Sandeep, You asked "What are" and "How to" but missed out asking "Why"? I suspect the only reason most people use classes is because they have yet to discover there are better ways, just as advised in the Gang of Four.

Collapse
Β 
jonrandy profile image
Jon Randy πŸŽ–οΈ β€’ β€’ Edited

JS is still only 'emulating' classes using prototypes. The Class syntax that was introduced is just sugar over the existing prototype stuff - which is still being used underneath.

Collapse
Β 
sandeepnautiyal profile image
Sandeep Nautiyal β€’

Hey @jonrandy ,

Spot on about classes being fancy talk for prototypes! But they definitely have some perks, like:

Clearer Code: The class syntax makes your objects way easier to read and understand. No more squinting at prototype chains!
Better Organization: Classes keep everything nice and tidy by bundling data and methods together. Less code headaches for you!
OOP Magic: Classes make it a breeze to use those awesome object-oriented patterns like inheritance and polymorphism. πŸͺ„
Overall, classes are like a super friendly way to work with objects in JavaScript.

Collapse
Β 
jonrandy profile image
Jon Randy πŸŽ–οΈ β€’

Clearer if you are used to class-based inheritance. This kind of thing is completely subjective

Collapse
Β 
tracygjg profile image
Tracy Gilmore β€’ β€’ Edited

Hi @jonrandy, Is it still true to say "JS classes are just syntactic sugar on JS prototypes", I am not so sure?
I query the assertion following the introduction of private properties as I do not think these can be used with or have an idiomatic equivalent for prototypes.
As stated on the MDN page "Private properties were not native to the language before this syntax existed. In prototypal inheritance, its behavior may be emulated..."
Regards, Tracy

Collapse
Β 
zerosirus profile image
ZeroSirus β€’

*samaj me kuxh ni aya par sun ke accha laga *

Collapse
Β 
dknightemperor profile image
Azazul Haque β€’

It's nice Article, Keep writing stuffs you learn new.

Collapse
Β 
sandeepnautiyal profile image
Sandeep Nautiyal β€’ β€’ Edited

We'll do that 😁😁😁

Collapse
Β 
neerajsharma2000 profile image
Neeraj Sharma β€’ β€’ Edited

Informative article ,specially liked the humour .would be awesome if you highlight the main keypoints using bold/italic fonts.
Also,shouldnt classname start with uppercase letter as per convention?

Collapse
Β 
sandeepnautiyal profile image
Sandeep Nautiyal β€’ β€’ Edited

Hey @neerajsharma2000,

Thanks for the highlighting it, we'll be updating it, was a typo lol 😝😝