There is technically no class, they're both just functions. Any function can be invoked as a constructor with the keyword new and the prototype property of that function is used for the object to inherit methods from.

"Class" is only used conceptually to describe the above practice.

So when someone says to you "make a color class" or whatever, you would do:

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

Color.prototype.method1 = function() {

};

Color.prototype.method2 = function() {

};

When you break it down, there is simply a function and some assignments to a property called prototype of that function, all generic javascript syntax, nothing fancy going on.

It all becomes slightly magical when you say var black = new Color(0,0,0). You would then get an object with properties .r, .g and .b. That object will also have a hidden [[prototype]] link to Color.prototype. Which means you can say black.method1() even though .method1() does not exist in the black object.

Answer from Esailija on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Classes
Classes - JavaScript - MDN Web Docs
Classes are in fact "special functions", and just as you can define function expressions and function declarations, a class can be defined in two ways: a class expression or a class declaration.
🌐
W3Schools
w3schools.com › js › js_classes.asp
JavaScript Classes
Functions Advanced Function Definitions Function Callbacks Function this Function Call Function Apply Function Bind Function IIFE Function Closures Function Reference Function Quiz JS Objects · Object Study Path Object Definitions Object this Object Iterations Object Get / Set Object Management Object Protection Object Prototypes Object Reference JS Classes
Discussions

What is the difference between "class" and "constructor function" in js? I tried looking up on YT but found nothing relevant atlest for me.
The main differences: syntax: class syntax is cleaner, keeping everything together under a single class block and handling a lot of the boilerplate for you. safety: Code run in class definitions is always in strict mode. You also can't accidentally call a class constructor as a function or an error will be thrown. built-ins support/initialization: class initialization starts at the base class and works down to the derived class. This allows base classes to define the this (the new instance) which in turn allows class syntax to correctly support extending built-ins like Array. Alternatively, function constructors create the instance in the derived class and pass it up to the base for initialization so a base class has no influence over what this is. feature support: class syntax can support features that function constructors don't, in particular private members . The upcoming support for decorators is also only for class syntax. Some other smaller differences: When using toString() class functions will always use the class syntax (though shouldn't be too surprising since toString() defaults to showing the source of the function) The prototype on a class-defined constructor is defined as read-only. whereas function prototype properties are not function declaration definitions are hoisted, class declaration definitions are not Being in a class block allows a local name binding for the class (assuming its named) to be available to all members defined within the class block More on reddit.com
🌐 r/learnjavascript
20
31
May 16, 2022
Functions v/s Classes in JavaScript
In JavaScript, class is just a helper for easy creation of object constructor and prototype. While it can replace function based constructor, it can not fully replace prototype creation, as it doesn't have any way to define property descriptors. More on reddit.com
🌐 r/learnprogramming
9
1
August 11, 2022
Ways of creating a js class
Hi. I have seen two way of creating a class that we can later instantiate as objects but they are different. I was wondering which one I am supposed to use. //W3 schools class Person { constructor(name, age) { this.name = name; this.age = age; this.updateAge = function () { this.age++; }; } ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
March 31, 2021
when and why use the class with JavaScript, kindly help
Object Oriented Programming (OOP) is a coding pattern based primarily on the idea that state (i.e. properties) should be encapsulated with logic (i.e. methods). This is often contrasted with Functional Programming (FP), where state (i.e. data/variables) is kept separate from logic (i.e. functions). OOP is often written with the class syntax, but it has not much at all to do with the data structure JavaScript calls "objects" ({}), which in other languages are usually referred to as dictionaries, hash maps, or associative arrays. So if we are using class, it is not because we want to create a JS object, it is because we want to follow the OOP pattern and encapsulate state with logic. Let's look at an example: class Rectangle { constructor(length, width) { this.length = length; this.width = width; } getArea() { return this.length * this.width; } } let rect = new Rectangle(2, 3); console.log(rect.getArea()); // 6 So here, the concept of rectangleness is encapsulated within the class Rectangle. It includes both state (length/width) and logic (calculating an area). The code outside of this class does not need to know any of the details of what it means to be a rectangle. It only needs to know the interface (i.e. the constructor, methods, and public properties), and it can forget about any internal details. This is what "encapsulation" means, and is one of the major goals of OOP. Contrast this with an FP approach to the same problem: function getArea(rectangle) { return rectangle.length * rectangle.width; } let rect = { length: 2, width: 3 }; console.log(getArea(rect)); // 6 You trade some encapsulation for simplicity and composability. The getArea function only cares that you pass it an object with a length and a width. It doesn't care if you built it with a Rectangle class or a Square class or just a vanilla object. Since the function is stateless, it becomes much easier to test and reason about as well. The same work can be accomplished with both approaches, or indeed a mix of the two. Whether or not you use a class will come down to what patterns you prefer to work with or your team prefers to work with. More on reddit.com
🌐 r/learnjavascript
31
25
January 14, 2024
Top answer
1 of 7
47

There is technically no class, they're both just functions. Any function can be invoked as a constructor with the keyword new and the prototype property of that function is used for the object to inherit methods from.

"Class" is only used conceptually to describe the above practice.

So when someone says to you "make a color class" or whatever, you would do:

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

Color.prototype.method1 = function() {

};

Color.prototype.method2 = function() {

};

When you break it down, there is simply a function and some assignments to a property called prototype of that function, all generic javascript syntax, nothing fancy going on.

It all becomes slightly magical when you say var black = new Color(0,0,0). You would then get an object with properties .r, .g and .b. That object will also have a hidden [[prototype]] link to Color.prototype. Which means you can say black.method1() even though .method1() does not exist in the black object.

2 of 7
25

JavaScript is the most popular implementation of the ECMAScript Standard. The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.


Overview

« ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture. A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system.

ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. A web browser provides an ECMAScript host environment for client-side computation including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output.

ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects

Objects «

  • Each constructor is a function that has a property named “prototype” that is used to implement prototype-based inheritance and shared properties.

  • Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.


Function

JavaScript treats functions as first-class objects, so being an object, you can assign properties to a function.

Hoisting is the JavaScript interpreter’s action of moving all variable and function declarations to the top of the current scope. Function Hoisting, declarations & expressions

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }

ES5 Function:

function Shape(id) { // Function Declaration
    this.id = id;
};
// prototype was created automatically when we declared the function
Shape.hasOwnProperty('prototype'); // true

// Adding a prototyped method to a function.
Shape.prototype.getID = function () {
    return this.id;
};

var expFn = Shape; // Function Expression
console.dir( expFn () ); // Function Executes and return default return type - 'undefined'

To a function if the return value is not specified, then undefined is returned. If the function is invoked with new and the return value is not an object, then this (the new object) is returned.

NOTE: A prototype property is automatically created for every function, to allow for the possibility that the function will be used as a constructor.

  • constructor « Function object that creates and initializes objects.
  • prototype « object that provides shared properties for other objects.
  • __proto__ « The proto property which points to its super object's prototype. If you open it up you will see that proto points to its super object variables and functions.

To access prototype methods of above crated function, we need to create object using new keyword along with constructor function. if you are creating Shape - Object using new keyword then it has an internal (or) private link to function's prototype Shape.

ES5 Constructor Function Classes: Function objects created using Function.prototype.bind

Shape.prototype.setID = function ( id ) {
    this.id = id;
};

var funObj = new Shape( );
funObj.hasOwnProperty('prototype'); // false
funObj.setID( 10 )
console.dir( funObj );

console.log( funObj.getID() );
/*
expFun                            funObj
    name: "Shape"                   id: 10
    prototype:Object
        constructor: function Shape(id)
        getID: function()
        setID: function( id )
    __proto__: function ()          __proto__: Object
                                        constructor: function Shape(id)
                                        getID: function()
                                        setID: function( id )
    <function scope>
*/

ES6 introduced Arrow function: An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors. ArrowFunction grammar production do not have a prototype property.

ArrowFunction : ArrowParameters => ConciseBody

  a => (a < 10) ? 'valid' : 'invalid'

  const fn = (item) => { return item & 1 ? 'Odd' : 'Even'; };
    console.log( fn(2) ); // Even
    console.log( fn(3) ); // Odd

Class

In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.

Babel is a JavaScript compiler. Use it to Transform ES6 to ES5 format BABEL JS (or) ES6Console.

ES6 Classes: ES2015 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.

class Shape {
  constructor(id) {
    this.id = id
  }

  get uniqueID() {
    return this.id;
  }
  set uniqueID(changeVal) {
    this.id = changeVal;
  }
}
Shape.parent_S_V = 777;

// Class Inheritance
class Rectangle extends Shape {

  constructor(id, width, height) {
    super(id)
    this.width = width
    this.height = height
  }
  // Duplicate constructor in the same class are not allowed.
  /*constructor (width, height) { this._width  = width; this._height = height; }*/

  get area() {
    console.log('Area : ', this.width * this.height);
    return this.width * this.height
  }
  get globalValue() {
    console.log('GET ID : ', Rectangle._staticVar);
    return Rectangle._staticVar;
  }
  set globalValue(value) {
    Rectangle._staticVar = value;
    console.log('SET ID : ', Rectangle._staticVar);
  }

  static println() {
    console.log('Static Method');
  }

  // this.constructor.parent_S_V - Static property can be accessed by it's instances
  setStaticVar(staticVal) { // https://sckoverflow.com/a/42853205/5081877
    Rectangle.parent_S_V = staticVal;
    console.log('SET Instance Method Parent Class Static Value : ', Rectangle.parent_S_V);
  }

  getStaticVar() {
    console.log('GET Instance Method Parent Class Static Value : ', Rectangle.parent_S_V);
    return Rectangle.parent_S_V;
  }
}
Rectangle._staticVar = 77777;

var objTest = new Rectangle('Yash_777', 8, 7);
console.dir( objTest );

ES5 Function Classes: uses Object.defineProperty ( O, P, Attributes )

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Function instances that can be used as a constructor have a prototype property.

This property has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

    'use strict';
var Shape = function ( superClass ) {
    var currentClass = Shape;
    _inherits(currentClass, superClass); // Prototype Chain - Extends

    function Shape(id) { superClass.call(this); // Linking with SuperClass Constructor.
        // Instance Variables list.
        this.id = id;   return this;
    }
    var staticVariablesJOSN = { "parent_S_V" : 777 };
    staticVariable( currentClass, staticVariablesJOSN );

    // Setters, Getters, instanceMethods. [{}, {}];
    var instanceFunctions = [
        {
            key: 'uniqueID',
            get: function get() { return this.id; },
            set: function set(changeVal) { this.id = changeVal; }
        }
    ];
    instanceMethods( currentClass, instanceFunctions );

    return currentClass;
}(Object);

var Rectangle = function ( superClass ) {
    var currentClass = Rectangle;

    _inherits(currentClass, superClass); // Prototype Chain - Extends

    function Rectangle(id, width, height) { superClass.call(this, id); // Linking with SuperClass Constructor.

        this.width = width;
        this.height = height;   return this;
    }

    var staticVariablesJOSN = { "_staticVar" : 77777 };
    staticVariable( currentClass, staticVariablesJOSN );

    var staticFunctions = [
        {
            key: 'println',
            value: function println() { console.log('Static Method'); }
        }
    ];
    staticMethods(currentClass, staticFunctions);

    var instanceFunctions = [
        {
            key: 'setStaticVar',
            value: function setStaticVar(staticVal) {
                currentClass.parent_S_V = staticVal;
                console.log('SET Instance Method Parent Class Static Value : ', currentClass.parent_S_V);
            }
        }, {
            key: 'getStaticVar',
            value: function getStaticVar() {
                console.log('GET Instance Method Parent Class Static Value : ', currentClass.parent_S_V);
                return currentClass.parent_S_V;
            }
        }, {
            key: 'area',
            get: function get() {
                console.log('Area : ', this.width * this.height);
                return this.width * this.height;
                }
        }, {
            key: 'globalValue',
            get: function get() {
                console.log('GET ID : ', currentClass._staticVar);
                return currentClass._staticVar;
            },
            set: function set(value) {
                currentClass._staticVar = value;
                console.log('SET ID : ', currentClass._staticVar);
            }
        }
    ];
    instanceMethods( currentClass, instanceFunctions );

    return currentClass;
}(Shape);

// ===== ES5 Class Conversion Supported Functions =====
function defineProperties(target, props) {
    console.log(target, ' : ', props);
    for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function staticMethods( currentClass, staticProps ) {
    defineProperties(currentClass, staticProps);
};
function instanceMethods( currentClass, protoProps ) {
    defineProperties(currentClass.prototype, protoProps);
};
function staticVariable( currentClass, staticVariales ) {
    // Get Key Set and get its corresponding value.
    // currentClass.key = value;
    for( var prop in staticVariales ) {
        console.log('Keys : Values');
        if( staticVariales.hasOwnProperty( prop ) ) {
            console.log(prop, ' : ', staticVariales[ prop ] );
            currentClass[ prop ] = staticVariales[ prop ];
        }
    }
};
function _inherits(subClass, superClass) {
    console.log( subClass, ' : extends : ', superClass );
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, 
            { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
    if (superClass)
        Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

var objTest = new Rectangle('Yash_777', 8, 7);
console.dir(objTest);

Below code snippet is to test about Each instance has their own copy of instance members and common static members.

var obj1 = new Rectangle('R_1', 50, 20);
Rectangle.println(); // Static Method
console.log( obj1 );    // Rectangle {id: "R_1", width: 50, height: 20}
obj1.area;              // Area :  1000
obj1.globalValue;       // GET ID :  77777
obj1.globalValue = 88;  // SET ID :  88
obj1.globalValue;       // GET ID :  88  

var obj2 = new Rectangle('R_2', 5, 70);
console.log( obj2 );    // Rectangle {id: "R_2", width: 5, height: 70}
obj2.area;              // Area :  350    
obj2.globalValue;       // GET ID :  88
obj2.globalValue = 999; // SET ID :  999
obj2.globalValue;       // GET ID :  999

console.log('Static Variable Actions.');
obj1.globalValue;        // GET ID :  999

console.log('Parent Class Static variables');
obj1.getStaticVar();    // GET Instance Method Parent Class Static Value :  777
obj1.setStaticVar(7);   // SET Instance Method Parent Class Static Value :  7
obj1.getStaticVar();    // GET Instance Method Parent Class Static Value :  7


Major Differences between functions and classes are:

  • Function Declarations get Hoisted to Top of the context, where as classes declarations and function Expressions are not Hoisted.
  • Function Declarations, Expression can be Overridden as they are like a Variable - var if multiple declaration are available then it overrides its parent scope. Where as the Classes are not Overridden they are like let | const, let doesn't allows multiple declaration with same name inside its scope.
  • Function's / classes allows only single constructor for its object scope.
  • Computed method names are allowed to ES6 classes having class keyword, but function keyword is not allows it

    function myFoo() {
     this.['my'+'Method'] = function () { console.log('Computed Function Method'); };
    }
    class Foo {
        ['my'+'Method']() { console.log('Computed Method'); }
    }
    
  • JSON object & Object Literal
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Using_classes
Using classes - JavaScript - MDN Web Docs - Mozilla
January 23, 2026 - In JavaScript, classes are mainly an abstraction over the existing prototypical inheritance mechanism — all patterns are convertible to prototype-based inheritance. Classes themselves are normal JavaScript values as well, and have their own prototype chains.
🌐
Phpied
phpied.com › 3-ways-to-define-a-javascript-class
3 ways to define a JavaScript class / Stoyan's phpied.com
function Apple (type) { this.type = type; this.color = "red"; } Apple.prototype.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; Again, you can use the new objects exactly the same way as in 1. and 1.1. Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do: var o = {}; instead of the "normal" way: var o = new Object(); For arrays you can do: var a = []; instead of: var a = new Array(); So you can skip the class-like stuff and create an instance (object) immediately.
🌐
web.dev
web.dev › learn › javascript › classes
Classes | web.dev
Here, classes are special functions that serve as templates for creating objects that already contain data, properties associated with that data, and methods related to the manipulation of that data.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-classes
JS Classes In JavaScript - GeeksforGeeks
January 17, 2026 - Simplicity & Clarity: Provides a clear structure for creating and managing objects. A basic class that defines properties and methods. This example shows how to create an object with a constructor and method.
Find elsewhere
🌐
Modernjsbyexample
modernjsbyexample.net › book › 004-functions-classes
Functions and Classes - Modern Javascript by Example
function Animal(name, species) { this.name = name; this.species = species; } Animal.prototype.sayName = function() { console.log(this.name); } var Doggie = new Animal('Jeff', 'Dog'); There's nothing magical or new here, it's just different syntax for doing the exact same thing. Especially prevalent in modern JavaScript frameworks are static methods and properties. These are used to define properties and methods on the class itself, and not the instance.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-classes-in-javascript-handbook
How to Use Classes in JavaScript – A Handbook for Beginners
February 23, 2025 - In this article, we'll take a step-by-step approach, showing you how object-oriented programming is implemented in JavaScript with objects and constructor functions, and clearly illustrate why understanding and using classes will make you a more versatile and effective JavaScript developer, even if you’re used to writing everything in functions.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › classes
Class basic syntax
December 16, 2021 - The function code is taken from the constructor method (assumed empty if we don’t write such method). Stores class methods, such as sayHi, in User.prototype.
🌐
Medium
medium.com › @laasrisaid34 › javascript-class-vs-function-choosing-the-right-approach-for-your-code-eb048dcbc32d
JavaScript Class vs. Function: Choosing the Right Approach for Your Code | by Laasri said | Medium
June 12, 2023 - Functions are primarily used to group related pieces of code, perform calculations, and return values. They can also be utilized as callbacks, event handlers, or as the basis for functional programming paradigms.
🌐
Reddit
reddit.com › r/learnjavascript › what is the difference between "class" and "constructor function" in js? i tried looking up on yt but found nothing relevant atlest for me.
r/learnjavascript on Reddit: What is the difference between "class" and "constructor function" in js? I tried looking up on YT but found nothing relevant atlest for me.
May 16, 2022 -

So I am learning NodeJs and while creating a costum module which stores user data I created a constructor function in user.js

function User(name,age){
this.name = name;
this.age = age;
}

and in app.js I did

const User = require(//Path);

const user1 = new User("Adam",20);
console.log(user1.name);

but my consfusion begans when I used class in user.js like

class User{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}

but the code in the app.js remained similar with no errors.

So what is the point of classes in javasript? And how are they different form contructor functions.

Top answer
1 of 7
15
The main differences: syntax: class syntax is cleaner, keeping everything together under a single class block and handling a lot of the boilerplate for you. safety: Code run in class definitions is always in strict mode. You also can't accidentally call a class constructor as a function or an error will be thrown. built-ins support/initialization: class initialization starts at the base class and works down to the derived class. This allows base classes to define the this (the new instance) which in turn allows class syntax to correctly support extending built-ins like Array. Alternatively, function constructors create the instance in the derived class and pass it up to the base for initialization so a base class has no influence over what this is. feature support: class syntax can support features that function constructors don't, in particular private members . The upcoming support for decorators is also only for class syntax. Some other smaller differences: When using toString() class functions will always use the class syntax (though shouldn't be too surprising since toString() defaults to showing the source of the function) The prototype on a class-defined constructor is defined as read-only. whereas function prototype properties are not function declaration definitions are hoisted, class declaration definitions are not Being in a class block allows a local name binding for the class (assuming its named) to be available to all members defined within the class block
2 of 7
15
In most practical situations, there is little to no difference. Classes in Javascript are what is called syntactic sugar which means it's just a different way or representing the same thing.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › First-class_Function
First-class function - Glossary - MDN Web Docs
function sayHello() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); // Hello, JavaScript!
🌐
freeCodeCamp
freecodecamp.org › news › javascript-classes-how-they-work-with-use-case
JavaScript Classes – How They Work with Use Case Example
December 13, 2021 - Provides a proper way of generalizing classes. Allows flexibility for subclasses to implement whichever abstract function they need. The static keyword in JavaScript helps you define functions and properties in the class that cannot be called by the instance of the object.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions
Functions - JavaScript - MDN Web Docs
In JavaScript, functions are first-class objects, because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object.
🌐
DigitalOcean
digitalocean.com › community › tutorials › understanding-classes-in-javascript
Understanding Classes in JavaScript | DigitalOcean
August 26, 2021 - A JavaScript class is a type of function. Classes are declared with the class keyword.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Ways of creating a js class - JavaScript - The freeCodeCamp Forum
March 31, 2021 - Hi. I have seen two way of creating a class that we can later instantiate as objects but they are different. I was wondering which one I am supposed to use. //W3 schools class Person { constructor(name, age) { this.name = name; this.age = age; this.updateAge = function () { this.age++; }; } // Another tutorial function Person (name, age){ this.name = name; this.age = age; this.updateAge = function () { this.age++; }; }
🌐
Reddit
reddit.com › r/learnjavascript › when and why use the class with javascript, kindly help
r/learnjavascript on Reddit: when and why use the class with JavaScript, kindly help
January 14, 2024 -

As a frontend developer, I always use the functional programming style for my apps.

When I want to create an object, I just state a variable and fill it, such as let object = {}

I am really confused about why and when to use the class with JavaScript, if I use the class to create an object, things are going to be troublesome, I need to state a class and create an object by using it.
Kindly help why and when I should use the class and need some interprets

Top answer
1 of 13
36
Object Oriented Programming (OOP) is a coding pattern based primarily on the idea that state (i.e. properties) should be encapsulated with logic (i.e. methods). This is often contrasted with Functional Programming (FP), where state (i.e. data/variables) is kept separate from logic (i.e. functions). OOP is often written with the class syntax, but it has not much at all to do with the data structure JavaScript calls "objects" ({}), which in other languages are usually referred to as dictionaries, hash maps, or associative arrays. So if we are using class, it is not because we want to create a JS object, it is because we want to follow the OOP pattern and encapsulate state with logic. Let's look at an example: class Rectangle { constructor(length, width) { this.length = length; this.width = width; } getArea() { return this.length * this.width; } } let rect = new Rectangle(2, 3); console.log(rect.getArea()); // 6 So here, the concept of rectangleness is encapsulated within the class Rectangle. It includes both state (length/width) and logic (calculating an area). The code outside of this class does not need to know any of the details of what it means to be a rectangle. It only needs to know the interface (i.e. the constructor, methods, and public properties), and it can forget about any internal details. This is what "encapsulation" means, and is one of the major goals of OOP. Contrast this with an FP approach to the same problem: function getArea(rectangle) { return rectangle.length * rectangle.width; } let rect = { length: 2, width: 3 }; console.log(getArea(rect)); // 6 You trade some encapsulation for simplicity and composability. The getArea function only cares that you pass it an object with a length and a width. It doesn't care if you built it with a Rectangle class or a Square class or just a vanilla object. Since the function is stateless, it becomes much easier to test and reason about as well. The same work can be accomplished with both approaches, or indeed a mix of the two. Whether or not you use a class will come down to what patterns you prefer to work with or your team prefers to work with.
2 of 13
12
If you need the object to keep track of some state that the internal methods will reference, it’s easier with a class.
🌐
Quora
quora.com › What-are-the-advantages-of-using-a-function-over-a-class-in-JavaScript
What are the advantages of using a function over a class in JavaScript? - Quora
Summary Functions win for simplicity, closure-based privacy, flexible returns, composability, and often smaller/runtime-efficient code for small-to-medium use cases. Classes are better when you need shared prototype methods, inheritance, or explicit instance identity. Choose based on the problem’s complexity and the design primitives you need. ... Certified JavaScript Developer with 10+ years experience ·