Prototype-based vs Class-based programming In JavaScript.

·

2 min read

There are two different ways one can implement Object Oriented Programming in JavaScript, and this can cause a dilemma on which one to use. This article will help you understand the difference on both ways, then you can confidently take the style that works best for you, especially if you're new to JavaScript. This doesn't mean it can't be beneficial to an oldie but in most cases they already know what works for them. Alright lets dive in.

Object oriented programming is a style of programming were almost anything can be represented as an object. Lets take a look at objects in the real world - they are categorized (classes) and have properties (attributes) that define what they are. For example, a stone has weight, size, type, color, etc that makes it to be recognized as a stone different from other objects. Same way a person has height, complexion, name, race etc. Objects have a way of doing things or how they act, which in programming we call "methods" (or functions in functional programming). These actions can access and change some or all the properties of an object. Like, say, a person eats to gain energy.

JavaScript from the onset used a prototype-based style of writing OOP as compared to strict OOP (Object Oriented Programming) languages like Java and C++ that uses class. Class was introduced in JavaScript in the ES2015 version.

Pros and Cons of Prototype-based vs Class-based Programming in JavaScript.

  • OOP in JavaScript with classes has a rigid style which gives little chances for bugs while prototyping is flexible but has a higher chance of introducing bugs.
  • With classes you need a blueprint while prototyping is transparent and straight forward.
  • Classes has a clear syntax that makes OOP easier to grasp compared to prototyping.

It doesn't really matter which one you choose because using any of the styles you will still get the job done. Personally, I prefer classes for OOP in JavaScript because it makes code easier to read and write. I hope this has helped you get a better understanding on the two ways of writing OOP in JavaScript.