Continuing the discussion from freeCodeCamp Challenge Guide: Using Objects for Lookups:
I have updated this question to be more specific to concepts needed to understand coding (see that before the question was like I do not know the answer or where to go at all, please help and now there is a specific theory related concept). My original code is not here but an updated one is (after the instructions) through (a) chance or (b) critical thinking…
These are the instructions:
Using Objects for Lookups
Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to “lookup” values rather than a switch statement or an if/else chain. This is most useful when you know that your input data is limited to a certain range.
Here is an example of a simple reverse alphabet lookup:
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
Instructions
Convert the switch statement into a lookup table called lookup. Use it to lookup val and assign the associated string to the result variable.
My understanding is that alpha, bravo, etc. are strings and therefore use bracket notation?
Additionally, to be able to make result = lookup val, since they’re different to begin with, I need to set the values to each other? is it even neccesary to declare a variable if you’ve already declared it as a function?
Follow up question, then: Why create a variable “result”? why not directly return lookup?
I know this seems pedantic…could there be a shorter way to write this code
Here is my original bit of code:
// 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");
Instead can’t you do the following (within the function):
function **phoneticLookup(val)** = {
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");
As usual, I will continue to critical think…sometimes I even solve the problem myself after a while by typing it out like I just did. But I think I need help here.