Lukon
Lukon

Reputation: 265

Benefit of using bracket notation (with variables) to access a property of an object

While utilizing alternatives such as the dot operator make sense when needing to access some stored information, I'm having a little bit of difficulty understanding why and in what scenarios we would use variables to accomplish the same task.

For example:

var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2

versus:

var testObj = {

  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

var playerNumber = 16;      
var player = testObj[playerNumber];

Is it simply a matter of preference, or are there actual benefits to using each?

Upvotes: 0

Views: 2502

Answers (5)

mhodges
mhodges

Reputation: 11116

Bracket syntax allows you to dynamically access property names, whereas dot syntax does not. Here is an example of how it could be used:

var data = {
  prop1: "I am prop 1",
  prop2: "I am prop 2"
};
function clickHandler () {
  var prop = this.getAttribute("data-property");
  console.log(data[prop]); // <-- Dynamically access object properties with [] syntax
}

var buttons = document.querySelectorAll("[data-property]");
for (var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.addEventListener("click", clickHandler);
}
<button data-property="prop1">Get Prop 1</button>
<button data-property="prop2">Get Prop 2</button>

Bracket syntax also allows you the ability to use object properties that are otherwise invalid variable names (which is not recommended, but is doable).

For example:

var data = {
  "property name with spaces": "I'm a property with spaces",
  "another-invalid-variable-name": "I'm an invalid variable name"
};
console.log(data["property name with spaces"])
console.log(data["another-invalid-variable-name"])

Upvotes: 4

Mezo Istvan
Mezo Istvan

Reputation: 2772

It is usually based on preference, however I like to use bracket notation for arrays, and dot notation for objects. However if there is a property on the object with a dash in it, only bracket notation can be used.

foo = { "bar-baz": "value" };
foo["bar-baz"]; //returns "value"
foo.bar-baz; //error

Upvotes: 1

farisj
farisj

Reputation: 121

One thing that distinguishes them is that with dot notation, you have to already know the property you want to access.

Consider the instance where you may want to obtain user input or some other external factor to decide what property to obtain:

function myFunction(property) {

    var data = {
        thingOne: "1",
        thingTwo: "2"
    }

    return data[property];
}

In the above function, one could not write return data.property - it would look for a property called property! You'd have to use index notation to get the correct value.

Upvotes: 3

Phygon
Phygon

Reputation: 21

Bracket syntax is dynamic- It is typically used for collections, such as Lists, Arrays, Dictionaries, et cetera. Period notation is more useful for non-iterable fields, methods, and everything else you might want to access from a class.

For instance, you could iterate over a list with

var aggregate;
for (int i = 0; i < arrayOfNumbers.length; i++){
    aggregate += arrayOfNumbers[i];
}

Upvotes: 1

Michael Fourre
Michael Fourre

Reputation: 3015

The subscript syntax is more flexible than dot notation in a few ways. In your own example, performing some of the following operations is clearly impossible:

var playerNumber = 16;
var player = testObj.playerNumber; //null; this is equivalent to:
var player = testObj["playerNumber"]; //which is subscripting by the string "playerNumber"
var player = testObj[playerNumber]; //this is valid and produces the expected result: subscripting with the value 16

The dot notation is limited in that it cannot be used with variables holding dynamic values. testObj.playerNumber is not at all the same as testObj[playerNumber].

Upvotes: 0

Related Questions