Using Objects for Lookups - dot or bracket

Using Objects for Lookups - dot or bracket
0

#1
// 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;
  // Only change code above this line
  return result;
}

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

Hello!
I would like to know why I can’t use the dot operator on result = lookup.val;
I used the bracket notation and it worked fine, why doesn’t the dot operator work that way?


#2

@Omar507 dot notation doesn’t work for accessing with variables. See this: https://medium.com/@prufrock123/js-dot-notation-vs-bracket-notation-797c4e34f01d#.345fjpybx


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

Dot notation won’t work in your example because the lookup object has no property that’s literally called val. When you use lookup[val], you’re looking up property names that match the string value of val.


#4

Thanks a lot @dhcodes I just read that article and it really helped

I didn’t knew about the triple backticks, thanks for fixing it @kevcomedia!