Using Objects for Lookups - Simple question I guess

Tell us what’s happening:

Hello everyone and thank you for your help.

Ok I have a question, I have succeeded the using object for Lookups challenge but I do not understand why in my code below I could not use dot instead of bracket for accessing objet ? With dot it doesn’t work (result = lookup.val).

I tried with Bracket and it worked, but in the class it is said that we use bracket if there is space in the name of the object…

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

  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");

// Change this value to test
phoneticLookup(“charlie”);

Difference between . and bracket look up is ability to use quotes - ". With quotes you can tell computer that you are looking for this name specifically and not referencing variable that contains the name.

When you tried to use result = lookup.val it looked for property with key val inside lookup, not for val variable that contains the key. In other words, if you have object like this and try to access it:

let val = "someKey"
let myObj = {
  "val": "stuff",
  "vel": "more stuff",
  "someKey" : "some stuff"
}
let result = myObj.val;

Result will hold “stuff”, not “some stuff”, because in . notation you have no way to tell program if you are referencing variable or name key directly. Dot notation is specifically to access things by direct name, and brackets are to provide access with option to pass variable, because in brackets you can use " to distinguish between what you want, while with dot you don’t.

1 Like

Very clear thank you :slight_smile: