Using object literals as structs

One of the defining aspects of ECMAScript is the ability to add a field to any object, regardless of its origins, This "expando" aspect of the language can be extremely powerful—because it gives us unprecedented flexibility when using objects.

This aspect of the language can be used with great effectiveness in emulating the struct. Traditionally, a struct is similar to an object—it has properties (and in some languages, like C#, it can have methods also) that are accessible at run time.

The primary difference between an object and a struct (in a traditional language) is that an object is usually placed on the stack (and passed by reference), while a struct is placed on the heap (and is passed by value, like a primitive such as a number or string). There are subtle variations on this theme, but for the most part (and certainly for the purposes of this conversation) a struct follows this pattern.

Structs in ECMAScript

ECMAScript does not have the equivilent of a struct. However, because it supports the concept of object literals and expando fields, we can use an object literal where we would normally find a struct.

For instance, say we want to define a structure that represents a point in two dimensional space. There are two ways of doing this:

Of course, the latter can also be expressed using the object literal syntax.

OOP purists may argue that the first is always the correct one—because you are modeling something that has real world meaning. However, since a point usually only has two properties—X and Y—it can be much more expedient to use the latter.

In fact, using an object literal can be an extremely time-saving device, especially when the struct in question need only exist for a very short time, such as when passing it to a function:

function Translate(point){ ... }
var result = Translate({ X:23, Y:32 }) ;

The call to the Translate function above uses an object literal as if it were a struct to create a temporary object that only exists to execute the function. Once the function has finished (unless for some reason the function is designed to hold the reference to the point passed), the struct falls out of scope, and can be collected by the garbage collector.

Structs can also come in handy when you need a single construct to hold information for a period of time. For instance, if the developer needed a device to store a user's settings, he/she could use a struct to hold that information with ease.