Sitemap

JavaScript — Part 5

15 min readFeb 22, 2026

--

Press enter or click to view image in full size

Inheritance & extends Keyword in JavaScript:

What is Inheritance?

Inheritance means one class can take (inherit) properties and methods from another class. It helps avoid writing the same code again.

In simple words: A child class can use everything from a parent class.

What is extends keyword?

The extends keyword is used to create a child class from a parent class.

Example:

class Child extends Parent {}

This means: Child class will automatically have all methods and properties of Parent class (unless overridden).

Example: extends keyword is used to extends the properties of Animal to the Monkey.

Press enter or click to view image in full size

This code defines a base class Animal with properties (name, color) and methods (run, shout). The Monkey class extends Animal, meaning it inherits all its properties and methods while adding its own method eatBanana. Two objects are created: ani (an Animal) and mon (a Monkey). Calling ani.shout() prints that Tom is shouting, and mon.eatBanana() prints that Jack is eating a banana.

Example: another basic example of inheritance

Press enter or click to view image in full size

This example shows how a child class can inherit features from a parent class. The Vehicle class has a brand property and a start() method. The Car class extends Vehicle, so it automatically gets these features and also adds its own honk() method. When we create objects from these classes, the Vehicle object can only start, while the Car object can both start (inherited) and honk (its own method).

Example: another example of inheritance.

This example has three levels of inheritance:

Device → Phone → Smartphone.

The Phone class overrides the turnOn() method from Device, and the Smartphone class inherits that overridden behavior. Each class adds its own abilities, showing a layered, more advanced structure — all without using super().

Method overriding and Super keyword in JavaScript:

What is Method Overriding?

Method overriding happens when a child class writes its own version of a method that already exists in the parent class.

In simple words: Child class replaces the parent’s method with a new one.

Example idea: Parent has a speak() method → Child creates its own speak().

Why do we use Method Overriding?

· To change or customize the behavior of a parent method.

· To add extra features while keeping the parent functionality.

Example: a basic example of overriding

Press enter or click to view image in full size

extends Animal and overrides the speak() method by providing its own version that prints “Dog barks.” When we create an object d from the Dog class and call d.speak(), the overridden method in Dog is executed instead of the one in Animal, demonstrating how method overriding gives child classes more specific behavior.

What is super Keyword?

super is used to call the parent class’s constructor or methods.

Two places where super works:

1. Inside constructor → calls parent constructor

super(args)

2. Inside child method → calls parent method

super.parentMethodName()

Example: a basic example of super keyword.

Press enter or click to view image in full size

This code shows how the super keyword is used to call a parent class constructor in JavaScript. The Animal class has a constructor that sets the name property. The Dog class extends Animal and adds a new property, breed. Inside the Dog constructor, super(name) calls the Animal constructor so the name property is properly assigned before adding breed. When a new Dog object is created with “Bruno” and “Labrador”, it stores both values and prints them as output.

Example: overriding + using super in a method

In this example, the Animal class defines common properties like name and age along with an info() method to display them. The Dog class extends Animal, adding a new property breed and overriding the info() method to include breed information. Inside the overridden method, super.info() is used to call the parent class’s version before adding the dog-specific message. The class also includes a bark() method that belongs only to dogs. When a Dog object named Bruno is created, calling d.info() prints both the animal and dog details, and d.bark() shows its barking behavior.

Constructors in JavaScript:

What is a Constructor?

A constructor is a special function inside a class that automatically runs when you create an object.
Its job is to initialize the object (give it default values or setup).

In very simple words:
A constructor prepares the object when it is created.

Why do we use Constructors?

· To set initial values (name, age, model, etc.)

· To make sure every object starts with correct properties

· To avoid writing setup code again and again

Constructor Syntax

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

}

}

· constructor() → special method

· this.name → property of the object

· this.age → property of the object

Example: constructor only in employee class

This code defines an Employee class with a constructor that sets a name and age, and a method getInfo() that returns a short description. The Programmer class extends Employee, but because it has no constructor of its own, it automatically uses the parent class’s constructor. When you create new Programmer(“Alice”, 25), the values are passed to the Employee constructor, and getInfo() works because Programmer inherits all properties and methods from Employee.

Example: Constructor in BOTH Employee and Programmer

Press enter or click to view image in full size

This code defines an Employee class with basic properties, and a Programmer class that extends it by adding a new property, language. Since Programmer has its own constructor, it must call super(name, age) to run the Employee constructor before adding its own fields. When new Programmer(“Bob”, 30, “JavaScript”) is created, the object gets all Employee properties plus the language field, and getDetails() returns a descriptive sentence using all three values.

Example: Child Constructor Overriding Parent Constructor

This code shows a parent Employee class with a single name property, and a child Programmer class that extends it by adding a level property. The Programmer constructor must call super(name) to initialize the inherited name field before setting level. The class also includes a promote() method that increases the programmer’s level. When a new Programmer object is created with “Charlie” and level 1, it has both the inherited name and its own level, and calling promote() updates that level to 2.

Example: Constructor with default values

This code uses default values in constructors. The Employee class assigns default values for name and salary if none are provided. The Programmer class extends Employee and adds a new property, language, which also has a default value of “JavaScript”. When creating new Programmer(“Derrick”, 50000), only name and salary are passed, so the inherited fields are set accordingly, and language automatically becomes “JavaScript”. The resulting object contains all three properties: name, salary, and language.

Short Summary

· A constructor is a special method used to set up an object.

· It runs automatically when new is used.

· It initializes properties using this.

· super() is needed when using constructors in inheritance.

· If you don’t write a constructor, JavaScript creates one for you.

Static Method in JavaScript:

What is a static method?

· A static method is a function defined on the class itself, not on the objects created from the class.

· You call it using the class name, not the object.

Key points:

· You define them using the keyword static.

· You call them using the class name, not the object.

· They are useful for utility functions that don’t depend on instance data.

When to use static methods?

Use a static method when:

· The method does not depend on instance-specific data

· It’s a utility/helper function

· You need a way to create or manage instances

Examples:

· Math.random()

· Date.now()

Example: a very basic example. You created a class, you put a static method in it, and then you called it.

Press enter or click to view image in full size

Important Note:

1. You must call a static method using the class name, like this:

Hello.sayHi();

2. You cannot call it from an object like this:

let h = new Hello();

h.sayHi(); // This will NOT work

Static means: belongs to the class, not to the object.

Example: static method with parameters

· static add(a, b) is a static method.

· It takes two numbers and returns their sum.

· You call it using the class name, not an object.

Example: compare Static vs Non-Static

Press enter or click to view image in full size

getters, setters & instanceOf Operator in JavaScript:

Getters in JavaScript

A getter is a special method that lets you access a property like a variable, but behind the scenes a function runs. Used to return computed or formatted values.

Syntax

class User {

constructor(name) {

this._name = name; // “_” used to show it’s private-like

}

get name() { // getter method

return this._name.toUpperCase();

}

}

const u = new User(“aditya”);

console.log(u.name); // ADITYA (accessed like a property)

Key Points

· Accessed like a property: obj.property

· No need to call like a function.

· Good for computed values and hiding internal logic.

Example:

This code creates a Person class where the name is stored in a private-like variable _name. The getter name() lets you read the person’s name, and the setter name(value) lets you change it safely. When you create a new person (new Person(“Alice”)), the getter returns “Alice”. Then the setter updates the name to “Bob”, and the getter shows the updated value.

Setters in JavaScript

A setter allows you to set/update a property using simple assignment (obj.property = value). Used for validation, formatting, or controlling updates.

Syntax

class User {

constructor(name) {

this._name = name;

}

set name(value) { // setter method

if (value.length < 3) {

console.log(“Name too short!”);

return;

}

this._name = value;

}

}

const u = new User(“Adi”);

u.name = “Ak”; // too short → validation triggers

u.name = “Akshay”; // setter updates value

Key Points

· Used like a normal assignment.

· Good for validation & controlling updates.

· Usually paired with a getter.

instanceof Operator:

Checks if an object belongs to a specific class. Returns true/false.

Example:

instanceof checks whether an object was created from a certain class.

Since p was created using new Person(), p instanceof Person is true. And because all classes in JavaScript come from the built-in Object, p instanceof Object is also true.

IIFE — Immediately Invoked Function Expressions:

An IIFE is a function in JavaScript that runs immediately as soon as it is created. You don’t need to call it separately. It executes instantly.

Why is it called “Immediately Invoked”?

Because:

· The function is written

· And right after, it is called automatically

In short:

Function is defined + executed at the same moment.

Syntax

The most common IIFE format is:

(function () {

console.log(“I run immediately!”);

})();

Explanation:

· Function is wrapped inside () → makes it an expression

· Another () invokes it immediately

Where is IIFE used?

· To avoid global variables

· To create private variables

· To run setup code immediately

· To avoid variable conflicts in old JS (before modules)

Example: most basic example

Press enter or click to view image in full size

Destructuring assignment and Spread Operator:

What is Destructuring?

Destructuring allows you to extract values from arrays or objects and store them into variables easily.

It is just a short and clean way of writing:

· Take data from array/object

· Put into variables

· Without writing long code

Spread Operator (…)

The spread operator (…) is used to expand (spread) an array or object into individual elements. It spreads values out.

Get Aditya Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Difference Between Destructuring and Spread in Simple Words

Example: array destructuring

Press enter or click to view image in full size

Example:

Press enter or click to view image in full size

Example: printing something which is not there. It will give an error.

Press enter or click to view image in full size

Example: introducing “…rest”

Press enter or click to view image in full size

Example: skipping items.

Press enter or click to view image in full size

Example: default items.

Press enter or click to view image in full size

Example: destructuring object

Press enter or click to view image in full size

Example: renaming variables

Example: default values

Example: spread operator

Press enter or click to view image in full size

Example: merging array.

Press enter or click to view image in full size

Example: spread with object

Press enter or click to view image in full size

Local and Global Scope in JavaScript:

What is Scope?

Scope means where a variable can be accessed in your program. It decides which variables you can use and where.

Global Scope: A global variable is a variable that can be accessed from anywhere in the program.

How created?

· Declared outside any function/block

· Declared without let/var/const (not recommended)

Example: global variable

Press enter or click to view image in full size

Local Scope: A local variable is only accessible inside the block/function where it is created.

Types:

· Function scope → created inside a function

· Block scope → created inside { } using let or const

Example: function local scope

Press enter or click to view image in full size

Example: block scope

Press enter or click to view image in full size

let, const, var Scope Difference:

Example: Nested Scopes (Scope Chain): Inner scopes can access outer scope, but outer scope cannot access inner scope.

Press enter or click to view image in full size

Hoisting in JavaScript:

Hoisting means:

JavaScript moves variable declarations and function declarations to the top of their scope (before code runs). This allows you to use a variable or function before writing it in the code — but with different behaviors depending on var, let, const, and function types.

How Hoisting Works:

JavaScript has two phases:

1. Creation Phase (Memory Allocation Phase)

· JS scans the entire code.

· It allocates memory for:

o var declarations → set to undefined

o let/const → memory reserved but not initialized (they stay in the “Temporal Dead Zone”)

o function declarations → stored as complete functions

2. Execution Phase

· Code runs line by line.

· Variables get their assigned values during execution.

Why Hoisting Exists?

It helps JavaScript:

· scan code first,

· allocate memory,

· make functions available early.

It is part of JavaScript’s Execution Context creation.

Example:

Example: variable is declared later but used earlier, so gives ‘undefined’ as output.

Example: let is used in above example.

Closures in JavaScript:

What Is a Closure in JavaScript?

A closure is created when a function remembers and can access variables from its outer (parent) function — even after that outer function has finished executing.

Think of a closure as: A backpack that a function carries with it, containing the variables from where it was created.

In simple words:

· A function inside another function

· Inner function keeps access to the outer function’s variables

· Even when the outer function is no longer active

Why Closures Happen:

Closures happen because of how JavaScript works:

· JS creates a scope chain

· Inner functions keep a reference to their outer scope

· Nothing is deleted until JS sees no references

How Closures Work:

Step 1: You create a function inside another function

Step 2: The inner function uses a variable from the outer function

Step 3: You return the inner function

Step 4: Even after the outer function finishes, the returned inner function still remembers the outer variables.

Why Closures Are Useful

· Data privacy (private variables)

· Functions that remember state

· Memoization

· Event handlers

· Callback functions

· Module pattern

Example:

Why does this work?

Even though outer() finished,
inner() still remembers count → closure.

Arrow Functions Revisited:

Arrow functions are a shorter and cleaner way to write functions in JavaScript. They are written using the => (arrow) syntax.

They are mostly used for:

· short functions

· callbacks

· array methods

· improving readability

Example: both add and add2 are same.

Press enter or click to view image in full size

Example: arrow function with argument

Press enter or click to view image in full size

Example: passing two arguments to the arrow function

Press enter or click to view image in full size

Example: no parameters

Press enter or click to view image in full size

Example: one arguments

Press enter or click to view image in full size

Example: arrow function don’t have their own ‘this’, They use the this of the outer scope (lexical this). If we used a normal function inside setTimeout, it would NOT print the name correctly. Arrow functions fix that.

JavaScript on the server:

JavaScript was originally created to run only inside web browsers. But with the introduction of Node.js, JavaScript can now run outside the browser, on a server, just like other backend languages (Python, Java, PHP).

What Does “JavaScript on the Server” Mean?

It means using JavaScript to build the backend part of an application — the side that runs on a server, handles requests, talks to databases, and sends responses to users.

Why Node.js Allows This?

Node.js uses the V8 JavaScript engine (the same engine used in Chrome) and provides extra features:

· Access to computer files

· Ability to create servers

· Handle network requests

· Access to databases

· Manage packages using npm

This makes JavaScript a full-stack language (frontend + backend).

Press enter or click to view image in full size

Where Server-Side JavaScript Is Used

· Building APIs

· Making web servers

· Connecting with databases

· Authenticating users

· Sending emails

· Handling files

· Running background tasks

· Building real-time apps (chats, dashboards)

Why JavaScript on the Server Is Popular?

· One language for both frontend and backend

· Very fast because Node.js is event-driven

· Huge ecosystem (npm packages)

· Easy for beginners to start

Npm and Node.js packages:

What is npm?

npm (Node Package Manager) is a tool that comes with Node.js. It helps you install, update, and manage code packages created by other developers.

Think of it like an app store for JavaScript code.

What are Node.js Packages?

A package is a collection of reusable code that someone created for a specific purpose.

Examples:

· A package for sending emails

· A package for connecting to databases

· A package for creating servers

· A package for validating data

You install them using npm.

Why do we use packages?

Because instead of writing everything from scratch, you can use ready-made code.It saves time and reduces errors.

Example: to initialise the project

Press enter or click to view image in full size

Example: installing a modules

Press enter or click to view image in full size

Example: folder created because of installing the third party modules

Modules in JavaScript:

What Are Modules?

Modules are simply separate JavaScript files that you can import and export.They help you split your code into smaller, manageable parts.

Example:

· math.js → contains math functions

· main.js → uses those functions

This makes your project cleaner and easier to maintain.

Why Do We Need Modules?

· Avoids writing everything in one big file

· Helps reuse code

· Makes debugging easier

· Prevents name conflicts

· Makes code organized and professional

Types of Modules

1. ES6 Modules (import/export) — modern and recommended

2. CommonJS (require/module.exports) — used in Node.js (older)

We will focus on ES6 Modules.

How to Export Something

You can export:

  • variables
  • functions
  • classes

Example (math.js)

export function add(a, b) {

return a + b;

}

export const PI = 3.14;

How to Import Something

Example (main.js):

import { add, PI } from “./math.js”;

console.log(add(2, 3));

console.log(PI);

Important Rules for Modules

· Modules run in strict mode by default

· Imports must be at the top of the file

· File paths must include .js extension in browsers

· Each module has its own scope

Contact Me:
📧 Email: adii.utsav@gmail.com
🔗 LinkedIn: https://www.linkedin.com/in/aditya-kumar-3241b6286/
💻 GitHub: https://github.com/Rememberful

--

--

Aditya Kumar
Aditya Kumar

Written by Aditya Kumar

BTech | Security Software Engineer & Researcher | Cloud Security | Python, AWS, MERN, ReactJS | Mail: adii.utsav@gmail.com