JS Built-ins
DesignPatternsbeginner

Factory β€” Basic object creation

πŸ“– Usage Example
function createUser(name, role) {
  return { name, role, greet() { return 'Hi, I am ' + name; } };
}
const admin = createUser('Alice', 'admin');

A factory function returns a new object, hiding the creation logic from the caller.

Factory Pattern β€” Basic Object Creation

The Factory pattern encapsulates object creation. Instead of using new, you call a factory function that returns the object.

Challenge: Implement a createUser(name, role) factory function that returns a user object with name, role, and type: 'user' properties.

Example:

const user = createUser('Alice', 'admin')
user.type // 'user'
user.name // 'Alice'
user.role // 'admin'
πŸ’‘ Hints (3)
  • β€’ Return an object literal with all required properties
  • β€’ Use the parameters to populate the object
  • β€’ Each call to the factory creates a new object