Accessing JavaScript object properties indirectly

When it comes to accessing data in JavaScript objects there are two methods available

  • dot operator .
  • bracket notation []

Take as a example an object with the following properties:

var newObj = {
  propertyOne: "some string",
  propertyTwo: 2,
 "property Three" : "other string",
  4 : "Four"

Dot Operator

The dot operator is typical to method call chaining or tree style traversal.  It is useful when the name of the property is known.

newObj.propertyOne;   //  some string

Bracket Notation

The bracket notation is similar to the dot operator in the chaining process i.e. the object followed by property name.

object[propertyName][otherProperty]; // so on.

It is useful if the property name has a space in it (“property Three” for instance). But a more beneficial use is when the property’s name would vary, such as when iterating through a list.

 The bracket notation allows the use of variables as placeholders for a property’s name.

A simple example :

var placeHolder = "property Three";
newObj[placeHolder]; // yields "other string"

This is typical in a scenario  where a function is required to access or update an object’s properties. In building the function, the parameters would be generic and the dot operator would expect the exact name of a property to work. So a function signature with generic parameter names wouldn’t work:

function getProperties(ObjName, propName){
 var result = "The item you looked up is" +     ObjName.propName; 
 return result;

This simple example defeats the purpose of a lookup requiring only those two parameters itself, but the point is that using generic parameters means that this can be used in numerous contexts.

The dot operator used would result in undefined as the method would be looking for the specific property name.

The bracket notation, on the other hand, allows the use of variables containing the value of the property name assigned to it:

var placeholderName = propertyOne;var placeholderName = 1;

So this works well with parameter variables which would act as placeholders for a functions input.