Javascript Class

Working with classes in Javascript

About Javascript Class

  • Classes are a template for creating objects.
  • They encapsulate data with code to work on that data.
  • Classes are just like funcitons in javascript with special syntax.

Why to use Javascript Classes?

  • To encapsulate all related code
  • To reuse properties and methods in other classes via inheritance.
  • Better maintainability

Class Syntax

class ClassName {
  constructor() { ... }

Example class Country

class Country {
    constructor(name, population){ = name;
        this.population = population;

console.log(typeof Country);
// function
  • In above code we have create a class which is template to represent a country.
  • constuctor is special method which runs every time when an object is created for a given class.
  • this is special keyword which represents the instance of javascript class object.

Creating object for a javascript class

class Person{
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;

    // method to get full name
        return this.firstName + " " + this.lastName;

    // method to check if person is adult
        if(this.age >= 18){
            return true;
            return false;

// create object for above class
let john = new Person("John", "Bocasta", 45)
// John Bocasta
// true

// create another object for same class
let nani = new Person("Nani", "Ch", 8)
// Nani Ch
// false
  • In above code we have define a person class and created two different objects
  • new is keyword used to create an object for a class.