Main menu

Post navigation

JavaScript Object Creation: Patterns and Best Practices

This article was peer reviewed by Tim Severien. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

[author_more]

JavaScript has a multitude of styles for creating objects, and newcomers and veterans alike can feel overwhelmed by the choices and unsure which they should use. But despite the variety and how different the syntax for each may look, they’re more similar than you probably realize. In this article, I’m going to take you on a tour of the various styles of object creation and how each builds on the others in incremental steps.

Object Literals

The first stop on our tour is the absolute simplest way to create objects, the object literal. JavaScript touts that objects can be created “ex nilo”, out of nothing—no class, no template, no prototype—just poof, an object with methods and data.

var o = {
x: 42,
y: 3.14,
f: function() {},
g: function() {}
};

But there’s a drawback. If we need to create the same type of object in other places, then we’ll end up copy-pasting the object’s methods, data, and initialization. We need a way to create not just the one object, but a family of objects.

Factory Functions

The next stop on our tour is the factory function. This is the absolute simplest way to create a family of objects that share the same structure, interface, and implementation. Rather than creating an object literal directly, instead we return an object literal from a function. This way, if we need to create the same type of object multiple times or in multiple places, we only need to invoke a function.