Back to articles
What is a Constructor ?

What is a Constructor ?

via Dev.toSILAMBARASAN A

Introduction In JavaScript, a constructor is a special function or method used to create and initialize objects. Whenever you want to create multiple objects with similar structure, constructors help you do it easily and efficiently. Why Do We Need Constructors? Without constructors, you would have to manually create objects like this: let student1 = { name: "Silambu", age: 21 }; let student2 = { name: "sanjay", age: 22 }; This becomes repetitive and messy when creating many objects. Constructors solve this problem by providing a template (blueprint). Constructor Using Class (Modern Way) class Student { constructor ( name , age ) { this . name = name ; this . age = age ; } } let s1 = new Student ( " Silambu " , 21 ); console . log ( s1 ); Output: { name: "Silambu" , age: 21 } How It Works Internally When you write: let s1 = new Student("Silambu", 21); JavaScript does the following steps: Creates an empty object { } Sets this to point to that object Calls the constructor function Assign

Continue reading on Dev.to

Opens in a new tab

Read Full Article
0 views

Related Articles