5.15 Exercise: Function Factory and Constructor

In the previous exercise we used the object literal syntax to build an address. This time the goal is to create the very same address object in two different ways — once with a factory function, once with a constructor function. Try it on your own, then come back to compare.

1. Factory function

A factory function simply returns a new object. By convention it is named in camelCase (for example createAddress) and takes the data as parameters. When key and value share the same name, the shorthand syntax keeps the code clean:

function createAddress(street, city, zipCode) {
  return { street, city, zipCode };
}

const address = createAddress("...", "...", "...");
console.log(address);

2. Constructor function

  • Named in PascalCase (first letter of each word capitalised), so the convention is Address, not createAddress.
  • Uses the this keyword to assign properties on the new object.
  • Called with the new operator, which creates the empty object, binds this to it and returns it.
function Address(street, city, zipCode) {
  this.street = street;
  this.city = city;
  this.zipCode = zipCode;
}

const address = new Address("...", "...", "...");
console.log(address);

Log either result on the console and you'll see exactly the same shape: a plain object with three properties. The point of this exercise is simply to get comfortable with both syntaxes. In the next exercise, we'll work with blog publishing objects.