arrow_backward Back to blog

JS Fundamentals: JavaScript Objects and You

javascript

One of the most utilized, but not fully understood features of JavaScript is that, with a couple of exceptions, everything that you interact within the language behaves like an object.

This functionality can be seen most easily with Arrays and Functions. For example, the simple primitive version of Array (var arr = [1,2,3] for example) has object methods that can be used:

var arr = [1, 2, 3]; arr.indexOf(2); // >> 1 

Can I Use This Anywhere?

Before we get much further, letโ€™s cover the things that arenโ€™t objects. Simple primitives (boolean values (true and false), undefined, numbers, and strings) and null (which is itโ€™s own type) are not objects. Numbers, Strings, and Booleans can act like objects, in that they have methods, but these types are immutable. True objects are changeable (mutable), and their properties are a collection key/value pairs, expressed as {key: value}, or accessed through dot or array notation: key.value or key[โ€˜valueโ€™].

Here is an example of how Strings are not objects, but they are object-like:

var twoCities = "It was the best of times, it was the worst of times" twoCities.split(','); // >> ["It was the best of times", "it was the worst of times"]  // You can't add properties to Strings, but it acts like it's stored twoCities._author = "Charles Dickens"; // >> "Charles Dickens" twoCities._author // >> undefined 

This last case is important, because that aspect of mutable objects is what enables things like very simple caching on functions that perform complex tasks:

function renderTemplate (path) {   if (!renderTemplate.templates) {     renderTemplates.templates = {};   }    if (renderTemplate.templates[path] != null) {     return renderTemplate.templates[path];   }   var template = openAndReadFile(path);   return renderTemplate.templates[path] = template; } 

Because Functions are Objects, we can do this. If we wanted to do something similar with Strings, we cannot (and really, thereโ€™s not much need for it).

Leveraging Object-like Behavior to Your Advantage

Letโ€™s walk through our caching example in more detail to see how it helps us run more efficient code.

The renderTemplate Function

Here we have a function named renderTemplate, which returns an HTML fragment thatโ€™s read from a file stored on the file system. Since weโ€™re not focusing on how thatโ€™s done, but rather on how Functions being Objects is helpful, we are delegating the heavy lifting to a different method named openAndReadFile which handles the actual finding and opening of files. However, reading a file can be expensive and potentially redundant work, especially if youโ€™re looping through a large list of items that all use the same template.

Hereโ€™s the function again, for reference:

function renderTemplate (path) {   if (!renderTemplate.templates) {     renderTemplates.templates = {};   }    if (renderTemplate.templates[path] != null) {     return renderTemplate.templates[path];   }   var template = openAndReadFile(path);   return renderTemplate.templates[path] = template; } 

The first two lines, if (!renderTemplate.templates) { renderTemplates.templates = {}; } put this โ€œeverything is object-likeโ€ concept right in the forefront. First, the function is checking to see if it has a property named templates (note that you can reference named functions from within themselves, which is what weโ€™re doing here). If that property doesnโ€™t exist, it creates it, and stores an empty Object primitive as the initial value.

The function then checks the templates Object to see if thereโ€™s a reference to the template stored in the cache, and returns it if itโ€™s there. Then, if the template isnโ€™t stored in the cache, the openAndReadFile function is called and then simultaneously stored in the cache and returned to the context from which it was called.

Actually, Everything isnโ€™t an Object

This is a common misconception. JavaScript has six primary types: string, number, boolean, null, undefined, and object. Arrays and Functions are actually a variant of object, with Array being a sorted Object (and with itโ€™s own sub-set of rules) and Function a callable Object.

Further Reading

This is a topic thatโ€™s been covered in greater depth by other authors, and I highly recommend that you check out the following (and not just for this specific topic, either!)

arrow_backBack

New Project Request