Using Objects for Lookups ( .val vs [val] )

Tell us what’s happening:
Hey, can somebody tell me why “lookup.val” doesn’t work and “lookup[val]” - does here, "result = lookup[val];

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups

1 Like

I think that that is because with lookup.val instead of using the variable, it looks for a property named val. Whereas with crotchets (the square brackets) it sees (val) as a variable and then converts it to lookup.foxtrot or whatever value replaces val.

Why this is however? I have no idea. I haven’t completely finished the course yet.

3 Likes

Yes, what @Daehworra says. The square brackets say “evaluate what is in here”. The value in there is a variable, so it goes and gets the value of that. The value of the variable is string, so it can now go and look up to see if one of the keys in the object matches that string.

With the dot syntax, it goes to the object and sees if there is a key that matches the string of characters after the dot (up until the next dot if there’s another one, and so on), that’s all.

Logically, think about this: what would the value be here:

var value = "Hi";
var obj = {
  value: "Bye"
};

obj.value

There has to be some way to differentiate.

3 Likes

You explained it so much better @DanCouper!

Also, that’s a really good example!
I feel like I understand code better now even though I answered the question.

1 Like