Help for Using Objects for Lookups

Hello. Can someone help me understand this program. Why do I need the: var result = “”; line? If I take this line out the program still works. How does the line: result = lookup[val]; work? What does it do?

Spoiler
// 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("alpha");

Link to the challenge:

Please don’t post valid solutions in plain text to the forum, as it may spoil solutions for those trying to work them out for themselves.

var result = ""; declares the result variable and sets it to an empty string.

Your code may work without it, but what it actually does when it is undeclared is implicitly declare it on the fly in the global scope. Implicit global variables can catch you out or behave in ways you didn’t intend, so you should always declare your variables within the scope you are intending to use them.

You can also write it as var result; without setting it to an empty string, since the type doesn’t matter to ES5 JavaScript.

result = lookup[val] sets the value of the variable result to the value of the appropriate key in the object.

Each of the pairs in the lookup object represent a key : value pair. lookup[val] could also be written lookup['alpha'] (if the val was ‘alpha’). You can get the same value using dot notation instead of bracket notation: lookup.alpha - both of these will return "Adams".

Does that make sense?

Edit Damnit…@camperextraordinaire types faster than me :slight_smile:

3 Likes

Thank you for you help.:grinning: I have some more questions.

Does ‘val’ = the appropriate pair (e.g. “alpha”: “Adams”) or does it just = the second half of the appropriate pair (e.g. “Adams”)?
Is the key of an object just the first part of a pair (e.g. “alpha”) or the whole pair (e.g. “alpha”: “Adams”)?

Yes, the key is the first of the pair, and the value is the second. Val just represents the value.

What is the purpose of putting ‘val’ in: function phoneticLookup(val)?

Since ‘val’ is put in the function phoneticLookup(val), the parameter ‘val’ is capable of being used in the function. If ‘val’ wasn’t put in the function phoneticLookup(val) then it wouldn’t be capable of being used in the function. Is this correct?

Would ‘alpha’ be the key in the lookup object and “Adams” the value in the lookup object?

Yes, that’s correct.