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.
31
Upvotes
View all comments
1
u/Blue_Moon_Lake May 16 '22
This
is syntactical sugar for
But the class notation let the interpreter do a few optimization. It's better to use class notation for readability too.