Get updates

Scott JavaScript Variables and Anonymous Objects

JavaScript is not Ruby, but it does offer syntax that can lead to expressive code. There’s one case where JavaScript could have gone a step further and given us even more expressive code syntax, when dealing with object literals or anonymous objects.

There are a couple ways to create an object in JavaScript. JavaScript objects, by the way, are actually associative arrays, or hashes, and fantastically useful – but that’s another topic.

One is to use the Object constructor:

var item = new Object();

Or you could just employ an object literal via a pair of braces:

var item = {};

This is the preferred method, and it also makes the code look cleaner. The braces on their own can be used anywhere you need an object, such as the argument to a function call:


Such an object can be said to be without name, hence anonymous; assigning it to a variable “names” it.

An Object Literal with Properties

Part of the JavaScript object literal syntax is the ability to specify properties:

var purple_item = { 'color': 'purple' };

Where “color” becomes a property of the object assigned to purple_item, and the value of that property is ‘purple’. That property is accessible two ways:

purple_item.color === 'purple'
purple_item['color'] === 'purple'

When creating the object literal, enclosing the name of the property in quotes is optional (unless the property name also happens to be a JavaScript reserved word, like class):

var purple_item = { color: 'purple' };

An Object Literal with Variable Properties?

Sometimes it’s desirable to create an object with a property based on a variable values. For example, at work recently I had a function which toggles multiple “items”, accepting a hash of item IDs whose boolean values indicated whether to show or hide the item:

function toggleItems(stateByID)
    //iterate over the properties ("keys", aka item IDs) and show or hide each

toggleItems({ item_42: true, item_44: false });

Calling that function to toggle a single item is all right, but the code can be made a little more expressive by adding a singular version as a convenience function:

function toggleItem(id, state)
    toggleItems({ id: state }); //wrong!

The problem with this function is that it calls toggleItems with an object whose property is ‘id’, not the value of the id variable. Unfortunately JavaScript doesn’t allow the syntax needed to create an object literal with a property based on the value of variable. You have to do something like this instead:

function toggleItem(id, state)
    var stateByID = {};
    stateByID[id] = state;

One Response to “JavaScript Variables and Anonymous Objects”

  1. closet cleaners brockhampton

    JavaScript Variables and Anonymous Objects – Development – 3DM Design

Leave a Reply