Why we can't use here dot operator? not only here but also in various problems i have seen dot or [ ] doesn't work same, only anyone of these worked

// Setup
function phoneticLookup(val) {
  var result = "";

  // Only change code below this line
  var lookup={
    "alpha": "Adams",
    "bravo": "Boston",
    "charlie": "Chicago",
    "delta": "Denver",
    "echo": "Easy",
    "foxtrot": "Frank",
  }
  result=lookup[val];  // doesn't work for lookup.val
  return result;
}

// Change this value to test
phoneticLookup("charlie");

The difference is that the dot notation will use what you have written for s literal search of a property with that name
So you can use lookup.alpha because there is a property literally called “alpha” but you can’t use lookup.val because there is not a property called “val”
Instead bracket notation will evaluate what’s inside the brackets before accessing the value of the property

So

var variable = "alpha";
lookup[variable];

Because the bracket notation evaluates what’s inside the brackets, and will access a property called “alpha” because that is value of the variable

2 Likes

so dot we should use to directly to access the object properties(direct property name should be used) as it is not going to evaluate like that [ ] .

Bracket notation also is used if you have property names whit spaces

1 Like

can we used [ ] notation as
object[ prop1][prop2]
or
object[prop1].prop2

If prop1 and prop2 are both variables than you need to use bracket notation.
If prop2 is the exact property name then you can use dot notation (note that dot notation can’t be user if your property name includes spaces)

Yes, both are valid JS.

As stated, you can use the bracket notation with a variable. Leah said that it can also be used if the property name has spaces (something you can’t do with dot notation.) While that is a common way to think of it, the more accurate to say that while a property can be any valid JS string, to access it with dot notation, the property must be a valid JS identifier, that is (if I remember correctly) containing only letters, numbers, $, or _ and not starting with a number. Any property can be accessed with bracket notation.

1 Like