Classes in JavaScript- Use Class in JavaScript

No doubt, JavaScript is one of the popular programming languages with a number of useful features and advanced concepts. However, classes in JavaScript (ES6) may look like a new concept but it’s not.

ES6 (EcmaScript a standard on which JavaScript is built and) came with different new features such as- let, const, template strings and creating a class in JavaScript. That was the year 2015.

By the end of this post, you will learn- What is a JavaScript class? How you can solve complex problems by using them? and How to create a class in JavaScript with some meaningful examples.

So, let’s get started point by point-

Learning Points

 

What are classes in JavaScript?

If you’re working with JavaScript for at least a decent time, you might definitely build a couple of fundamental programs and functions, say- To add two numbers OR To print messages in console by calling some pre-defined functions like console.log().

Interview Key***
Do you know, what is console? It’s an object of class ‘Object’ that has some methods (or functions) to help us in debugging the JavaScript code.

To check the class name of any object in JavaScript, let’s say console, you can try with these techniques-

typeof console;                   // returns "object"
console instanceof Object;        // returns "true"
console.constructor === Object;   // returns "true"

 

In Short, JavaScript classes

Help you to manage all the properties (or say, the variables to store required information) and behaviors (the methods, to access properties – process them and – return desired results) of an entity (the object).

 

Still confused? What’s the actual use of JavaScript Classes?

Here is the basic layout of a Class with basic syntax –

JavaScript classes have a Layout.

Understand it with a housing example:

  • A class in JavaScript, is more like the blueprint for a house. Using this blueprint, you can build one or many houses as you like.
  • Each house you build (or instantiate, technically speaking) is an object, also known as an instance of that class.
  • Each house also has an address, of course. If you want to tell someone where the house is, you give them a card with the address written on it. You can assume that card as the object’s reference.
  • The house has some information about number of rooms, floors and is there a garden or not. These are properties of the house.
  • Sometimes, you wish to change the color of the house. Technically, You can perform this operation by defining a methodchangeColorTo( yourColor ).
  • And If you wish to visit the house, you look at the address written on the card. Technically, This is called dereferencing.

So far, you better understand, what exactly are classes in JS and what they do? Now, It’s better to write some code to solidify the syntax and other concepts as well.

 

Defining a JavaScript Class

Before jumping into a complete example of JavaScript classes, let’s first start with its building blocks-

Syntax:

To create a class in JavaScript, you’ll have to use a keyword class, then provide a name and define its body-

class YourClassName {
  constructor() { ... }
}

 

Constructor:

Another important component of a JavaScript class is a constructor. It’s a special method similar to a function but:

  • It must have the exact name “constructor”
  • Its main use is to initialize the object properties whenever a new object is created
  • That’s why its always gets invoked and executed automatically
  • No matter, whether you define a constructor method or not, JavaScript will implicitly add an empty constructor method.

Method:

Any regular JavaScript class contains a set of methods that are created with the same syntax as an object’s method. Here is how it look like-

class ClassName {

  constructor() { /* Some code */ }

  theFirstMethod() { /* Some code */ }

  theSecondMethod() { /* Some code */ }

  theNthMethod() { /* Some code */ }
}

 

Getters/Setters:

Classes may include getter (methods to get the values of its properties) and setter ( methods to set the values in its properties).

Here is an example with class House with its getters/setters and constructor.

Example:

class Home {

  constructor(name) {

    // it will invoke the setter...
    this.name = name;

  }

  get name() {

    // its getter...
    return this._name;

  }

  set name(value) {

    // its setter...
    if (value.length < 3) {
      alert("Choose a bit longer name for House!");
      return;
    }
    this._name = value;
  }

}

// its use...
let yourHome = new Home("Ena");
alert(yourHome.name);            // Ena

yourHome = new Home("");         // Choose a bit longer name for House!

 

 

Is there any alternative to a JavaScript class?

There’s no doubt, classes in JavaScript play a vital role in quick and better understanding, but this is also true, that it’s not mandatory to use a class all the time.

You can also achieve the same results by implementing similar to this using functions-

Example:

// Rewriting class Home using pure functions

// Step 1. Create constructor function
function Home(name) {
    this.name = name;
}

// By default, a function prototype has "constructor" property,
// so you don't need to create it

// Step 2. Add the method to prototype
Home.prototype.tellName = function() {
    alert(this.name);
};

// Final Step. Usage:
let myHome = new Home("ShubhamKLogic");
myHome.tellName();      // displays a popup box with messege "ShubhamKLogic".

This was actually a JavaScript class vs function, as we have implemented the exact same housing problem using JS functions only.

 

Wrap Up 

As a summary, Classes, in any programming language, are a piece of code that encompass multiple objects, methods and allow manipulation for its member variables and functions.

So far, we have learned, JavaScript class fundamentals, JavaScript class constructor, How do classes work in JavaScript? and a number of other sub-concepts as well.

If you have any doubt related to JavaScript Classes and their programs, just write them in comment box below or via Google Form, and I’ll try my best to give you the solution within a day.

Similar related useful JavaScript articles you may like-

Leave a Comment