Daily Tips & Tricks for Web Enthusiasts

Access Object Properties with Variables

Typically object properties in JavaScript are accessed using the dot notation, like this:

var object = {
    foo: 'bar'
};

var example = object.foo; // example is now 'bar'

But what if you don’t know the property name at runtime?

Let’s say you wanted to write a function called propertyOfObject() that took two arguments, object and propertyName, and returned the value of the specified property. Dot notation won’t work in a situation like this:

function propertyOfObject(object, propertyName) {
    return object.propertyName; // This doesn't work!
}

That would look for a property that was literally named propertyName, which is not what we want.

The solution is to use bracket notation to access the property value, like so:

function propertyOfObject(object, propertyName) {
    return object[propertyName]; // Bingo.
}

Any object property can be accessed using bracket notation, and you can put any expression you want inside the brackets, as long as that expression evaluates to a string for the property you’re after. All of the following are valid approaches:

object['foo'];
object[propertyName];
object[someFunctionThatReturnsAPropertyName()];

Now you can access object properties at runtime without knowing their names in advance.