JavaScript Object lookup questions

Tell us what’s happening:
So my problem with this is that I don’t know why at the end result = lookup[val]; works? What are we calling with [val] the parameter? Are we changing the variable to “result” to now equal lookup[val]? If so, why cant i change var result = lookup[val] at the top? I feel like a lot of this was just never explained or covered. I’ve looked back in my notes and nowhere is there a mention of just changing a variable by just declaring it again with out var in front of it, unless I’m missing something…Sorry if this post is a mess I’m just getting super discouraged and frustrated with JavaScript lately, I feel like I’m hitting a roadblock in my brain every 10 minutes, any help would be appreciated.

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];//why does this work?

// Only change code above this line
return result;

Your browser information:

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

Challenge: Using Objects for Lookups

Link to the challenge:

You aren’t declaring the variable again, you are updating the value stored inside the variable. This ability to do so is critical to the idea of a variable. The value in a variable needs to be able to vary (there are exceptions, which will be covered later).

In this example, you are using key/value storage to look up the string that corresponds with the phonetic alphabet letter. For instance, alpha corresponds to "Adams". The syntax result = lookup[val] is the syntax to find the string value result that corresponds to the key val.

You can’t use the syntax result = lookup[val] until after the variable lookup has been declared. Since the variable result has already been declared at this point, you need to update the value stored in result to match the result from the lookup.

I hope this helps, but please let me know if I can be clearer.

1 Like

That does make sense, just felt like I was missing some critical information in order to complete this problem. I guess I kind of knew that the value of a variable could vary but I just forgot, but I didn’t know that you can attach/call a parameter declared in a function to a variable ie: lookup[val]. I also don’t feel like that was explained very well in the sessions leading up to this problem, but I guess I know that now.

1 Like

Coding is all about that iterative process of understanding.

accessing object properties with variables is in previous lessons
and this is what that is
accessing an object property with a variable

1 Like