Using Objects for Lookups v2020

Continuing the discussion from freeCodeCamp Challenge Guide: Using Objects for Lookups:

From this discussion above, the answer is to assign lookup[val] to result variable:

result = lookup[val];

Before I viewed the discussion, my code was:

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

  lookup[val];
  var result = val;
  console.log(lookup[result]);  
  // Only change code above this line
  return result;
}

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

The answer in my console is Denver when val = "delta" and so on.
But why my code is not accepted as the correct answer?

Thanks in advance! :slightly_smiling_face:

the output of the function depends on the return statement

look at your return statement:
return result

and you have defined result as
var result = val;

the console.log prints to the console but doesn’t determine the output of the function (it is useful for debugging purposes, as it can show values that variables have at each step)

Hi,

I get console.log is useful for debugging process.

But I still don’t understand this part:

the return statement is return result so to see what is that the function returns (which is what counts), you need to check what’s the value of result

result appear for the first time in the line var result = val and then never changed, so at the end you are just returning val

you have these two lines, but they don’t do anything about changing values or establishing the returned value of the function
the line lookup[val] does nothing at all, and the line console.log(lookup[result]) will just print that to the console, so in terms of the returned value of the function it doesn’t do anything

I think I’m getting near…

The reason I get the result is because I put the console.log inside the function. If I put it outside the function, it won’t show me the result because the result is not showing anything…correct me if this is not right.

I think I get it now. If we put result = lookup[val], then every time the val changes, the function always return the value for the val.

I hope I understand it now.

the variable result exist only inside the function, so if you put console.log(result) outside the function, you get an error

to see the output of the function you need to write console.log(phoneticLookup("alpha")) (you put the function call inside the console log statement so that the output is printed to the console)

2 Likes

return result = lookup[val];

When the val is “alpha” , the function will check the value for “alpha” then return the value.

Is this right?

yes, that’s what in happening, but be sure to understand that it’s just an object, and lookup[val] is just how you access an object property