JavaScript Constructor & the new Operator
In JavaScript, the constructor function and the new operator are used to create objects efficiently.
1️⃣ What is a Constructor Function?
A constructor function is a regular function used to create multiple objects with the same properties and methods.
🔹 Naming Convention: Constructor functions start with a capital letter.
🔹 Must be used with new to create objects.
✅ Example: Creating a Constructor Function
📌 Key Points:
✅ this.name = name; → Assigns properties to the object.
✅ this.introduce = function() {...} → Adds a method.
✅ new Person("Alice", 25); → Creates a new object.
2️⃣ How the new Operator Works
When calling a function with new, JavaScript does four things automatically:
- Creates a new empty object:
{} - Sets
thisto reference that object - Adds properties & methods to the object
- Returns the new object
Example without new:
Example with new:
3️⃣ Adding Methods to the Prototype
Instead of defining methods inside the constructor (which creates a new copy for every object), use prototype to save memory.
📌 Why use prototype?
✅ Saves memory (single method shared by all objects)
✅ Efficient performance
4️⃣ Checking if an Object was Created with new
Sometimes, a function might be called without new by mistake. You can check if new was used with instanceof.
📌 instanceof checks if an object was created from a constructor.
5️⃣ Returning a Custom Object from a Constructor
Normally, constructors return this automatically. But if you return an object, it replaces this.
📌 If a primitive value is returned, it's ignored.
6️⃣ Summary
✔ Constructor functions create multiple objects
✔ Use new to create an object
✔ Methods should go inside prototype for efficiency
✔ Use instanceof to check object creation
✔ Returning an object from a constructor replaces this
🚀 Now you’re a pro at JavaScript constructors & new! Let me know if you need more examples. 😊

