Factory Function

2021-10-05

A factory function is a function that returns an object. A common way to define this kind of function is using the prefix create followed by the "what" the function will fabricate. For example:

let createUser = (name, email) => ({
  name,
  email
})

createUser('Gustavo', 'gustavo@email.com')
// {name: "Gustavo", email: "gustavo@email.com"}

If you want to avoid any client of createUser by modifing it's returned object properties, you can freeze the returned object:

let createUser = (name, email) =>
  Object.freeze({
    name,
    email
  })

let user = createUser('Gustavo', 'gustavo@email.com')
user.name = 'John'
user // {name: "Gustavo", email: "gustavo@email.com"}

Using the closure context, you can use either name and email variables to return a pretty version of name and e-mail (I removed Object.freeze call to avoid unnecessary noise):

let createUser = (name, email) => ({
  name,
  email,
  pretty: () => `${name} <${email}>`
})

createUser('Gustavo', 'gustavo@email.com').pretty() // "Gustavo <gustavo@email.com>"

You can also hide variables inside the createUser closure context by not returning them in the returned object:

let createUser = (name, email) => {
  let password = '****'
  let pretty = () => `${name} <${email}>`

  return { name, email, pretty }
}

createUser('Gustavo', 'gustavo@email.com')
// {name: 'Gustavo', email: 'gustavo@email.com', pretty: ƒ}
#design pattern#typescript#javascript

📝 Edit this page