Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Classes
Next article icon

JavaScript Classes

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript classes (introduced in ES6) provide a structured way to create objects with shared properties and methods. They support inheritance, encapsulation, and modularity, making it easier to write object-oriented code.

Syntax

class ClassName {
constructor() {
// Initialize properties here
}
// Define methods here
methodName() {
// Method code
}
}
  • The class keyword is used to declare a class.
  • The constructor() method is a special method that is automatically called when an instance of the class is created.
  • You can define methods inside the class to provide behaviour for objects created from the class.

Key Features of JavaScript Classes

  • Encapsulation: Bundles data (properties) and behaviour (methods) together.
  • Constructor Method: Initializes properties when an object is created.
  • Inheritance: Allows one class to inherit properties and methods from another.
  • Code Reusability: Enables the creation of multiple instances with shared functionality.
  • Simplicity & Clarity: Provides a clear structure for creating and managing objects.

Creating a Simple Class

A basic class that defines properties and methods. This example shows how to create an object with a constructor and method.

JavaScript
class Person {     constructor(name, age) {         this.name = name;         this.age = age;     }     g() {         console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);     } } let p1 = new Person("Pranjal", 20); p1.g(); 

Output
Hello, my name is Pranjal and I am 20 years old. 
  • The Person class has a constructor to set name and age, and a g method to log a greeting message.
  • An instance (p1) is created with new, passing "Pranjal" and 20, then calls g to print the greeting.

Constructor to Initialize Objects

The constructor is used to initialize the properties of the object when an instance is created.

JavaScript
class Car {     constructor(make, model, year) {         this.make = make;         this.model = model;         this.year = year;     }     d() {         console.log(`${this.year} ${this.make} ${this.model}`);     } } let my = new Car("Toyota", "Corolla", 2021); my.d(); 

Output
2021 Toyota Corolla 
  • The Car class has a constructor to initialize make, model, and year, and a d method to log the car's details.
  • An instance (my) is created with new, passing "Toyota", "Corolla", and 2021, then calls d to print the car's information.

Inheritance in Classes

Inheritance allows one class to extend another, inheriting its properties and methods while adding or overriding functionality.

JavaScript
class Car {     constructor(make, model, year) {         this.make = make;         this.model = model;         this.year = year;     }     di() {         console.log(`${this.year} ${this.make} ${this.model}`);     } } class ElectricCar extends Car {     constructor(make, model, year, batteryLife) {         super(make, model, year);         this.batteryLife = batteryLife;     }     d() {         console.log(`Battery life: ${this.batteryLife} hours`);     } } let tesla = new ElectricCar("Tesla", "Model S", 2022, 24); tesla.di() tesla.d(); 

Output
2022 Tesla Model S Battery life: 24 hours 
  • ElectricCar inherits from Car, using super to set properties and adds batteryLife and d method.
  • An instance (tesla) calls both di to display car details and d to show battery life.

Creating Multiple Objects from a Class

Using classes to create multiple objects with the same structure but different data.

JavaScript
class Car {     constructor(make, model, year) {         this.make = make;         this.model = model;         this.year = year;     }     d() {         console.log(`${this.year} ${this.make} ${this.model}`);     } } let c1 = new Car("Toyota", "Corolla", 2021); let c2 = new Car("Honda", "Civic", 2020); c1.d(); c2.d();  

Output
2021 Toyota Corolla 2020 Honda Civic 
  • The Car class initializes car details and has a d method to display them.
  • Two Car instances (c1 and c2) are created, and d is called on both to show their details.

Advantages of JavaScript Classes

  • Improved Code Organization: Classes provide a structured way to organize code, making it easier to understand and maintain.
  • Encapsulation: Classes allow bundling data (properties) and methods (functions) that operate on that data in one place, improving code clarity.
  • Reusability: Once a class is defined, you can create multiple instances (objects) with similar functionality but different data, promoting reusability.
  • Inheritance Support: Classes support inheritance, enabling code reuse and extension, reducing redundancy.
  • Easier Debugging and Testing: With a clear object-oriented structure, debugging and testing become easier, as each class is self-contained with its own behavior and properties.
  • Scalability: Classes are particularly useful for building large-scale applications by organizing code into manageable units.

Conclusion

JavaScript classes provide a clear and structured way to create and manage objects. With features like constructors, encapsulation, inheritance, and methods, they allow developers to write clean, reusable, and modular code. Whether creating simple objects or building complex hierarchies with inheritance, classes simplify object-oriented programming in JavaScript, making your code more maintainable and scalable.


Next Article
JavaScript Classes
author
_tanya_sri_
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics
  • JavaScript-Classes

Similar Reads

    Perl | Classes in OOP
    In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
    6 min read
    Understanding Classes and Objects in Java
    The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
    10 min read
    Java - Inner Class vs Sub Class
    Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMe
    3 min read
    Java Source File Structure
    Java source file structure describes that the Java source code file must follow a schema or structure. In this article, we will see some of the important guidelines that a Java program must follow.     A Java program has the following structure:  1. package statements: A package in Java is a mechani
    6 min read
    java.lang.reflect.Field Class in Java
    The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather t
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences