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

Creating objects one by one is a mistake.

If you write a manual object for every user or classmate, you repeat code. If you have 100 users, you write the same logic 100 times. This leads to bugs. You might accidentally change a property later and break your application.

Use these two patterns instead to write clean code.

  1. Factory Functions

Think of a real factory. Raw materials go in. A finished product comes out.

A factory function takes parameters and returns a new object.

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

The benefits:

  1. Constructor Functions

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

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

When you use "new", JavaScript does the work for you:

You do not need a "return" statement.

Scaling your code

You can combine these patterns with arrays to handle large amounts of data. Instead of typing every name, use a map function.

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

Now you have a list of objects ready to use.

Summary:

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