𝗙𝗮𝗰𝘁𝗼𝗿𝘆 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗻𝗱 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁

Creating objects one by one is a mistake.

If you have 100 classmates and need to create an object for each, writing individual objects leads to problems. You repeat your logic too many times. You also risk bugs. For example, you might accidentally overwrite a property name later in your code.

You need a better way to reuse logic.

Factory Functions Think of a factory. You put in raw materials and get a finished product. A factory function does the same. It takes parameters and returns a new object.

Example: function classFactory(name) { return { reply() { return ${name} is present } } }

This approach keeps the name safe. You cannot accidentally change the name because it stays inside the function scope. You write the logic once and reuse it many times.

Constructor Functions Constructor functions also create objects. They use the this keyword and the new keyword. By convention, these functions start with a capital letter.

Example: function Classmate(name) { this.name = name this.reply = function() { return ${this.name} is present } }

When you use the new keyword, JavaScript does the work for you. It creates a new object, assigns it to this, and returns it automatically. You do not need a return statement.

Scaling your code You can combine these methods with arrays to handle large amounts of data.

const names = ['Kali', 'Andrew', 'Pearl', 'Percy'] const classmates = names.map(name => new Classmate(name))

classmates.forEach(c => console.log(c.reply()))

This makes your code clean and scalable.

The main goal is simple:

Source: https://dev.to/pearlodi/factory-functions-and-constructor-functions-in-javascript-lmb