-2
var stooge = {
    "first-name": "Jerome",
        "last-name": "Howard"
};
var properties = [
    'first-name',
    'middle-name',
    'last-name',
    'profession'];
for (i = 0; i < properties.length; i++) {
    console.log(properties[i] + ': ' + stooge[properties[i]]);
}

I don't understand stooge[properties[i]]. Why are we using bracket before properties? Can someone explain when to use brackets?

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 4
    It is a way of accessing the properties of an object in javascript called Bracket notation.. Check this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators#Bracket_notation – PSL Apr 04 '14 at 20:42
  • `.` and `[]` are interchangeable, meaning `stooge.name` is the same as `stooge["name"]`. The thing is sometimes the property you want is not a valid JavaScript identifier (such as `first-name`) or is a variable (such as `properties[i]`). That's when your only choice is using the `[]` notation. – acdcjunior Apr 04 '14 at 20:42
  • In addition to what PSL stated, the same notation is used to access arrays, as well as objects. – Cypher Apr 04 '14 at 20:42
  • The same notation is used for Arrays because Arrays are Objects too. It's performing the same task in both cases. – cookie monster Apr 04 '14 at 20:55

3 Answers3

1

I dont understand stooge[properties[i]].

It means more or less literally what it says.

If i is 0, then properties[i] is properties[0], which is set to 'first-name'.

Therefore, stooge[properties[i]] is stooge[properties[0]] is stooge['first-name'] is "Jerome".

EDIT

As someone pointed out, you cannot use dot-notation here. The name of the property is first-name. If you typed stooge.first-name, the parser would interpret that as stooge.first - name. undefined minus undefined is... NaN!

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • You should mention what you commented on my answer. The question is why use brackets. Your explanation of why dot notation won't work would be useful and relevant. – Smeegs Apr 04 '14 at 20:59
0

This is just a way to access properties dynamically from an object. In this cause since there is an array of strings, it lets you get the value from the object. Since you can't do something like obj.'some-string'

This might help JavaScript property access: dot notation vs. brackets?

Community
  • 1
  • 1
Rchristiani
  • 424
  • 3
  • 18
-1

Object properties can be accessed with a .. or with [].

But dot notation won't work here.

because if you switch stooge[properties[i]] to stooge.properties[i] it would return undefined, because the stooge object doesn't have a member named properties.

Smeegs
  • 9,151
  • 5
  • 42
  • 78
  • 2
    Not in this case. The name of the property is `first-name`. If you typed `stooge.first-name`, the parser would interpret that as `stooge.first - name`. undefined minus undefined is... NaN! – Michael Lorton Apr 04 '14 at 20:45