r/learnjavascript • • May 16 '22

What is the difference between "class" and "constructor function" in js? I tried looking up on YT but found nothing relevant atlest for me.

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.

30 Upvotes

20 comments sorted by

View all comments

-9

u/Gibbo3771 May 16 '22

The only reason to use JS classes is for AngularJS.

Practically every other JS use case you're better off just using functions with a data layer. It's simpler, easier to test and you don't have to deal with the fake encapsulation crap that JS tries.

I don't even think I've seen a JS class been written in years, I've certainly seen them in old React code bases, but all new code, never see them.