I have a JavaScript challenge in freecodecamp that is probably really simple, but I still don't understand how to do it. It goes as follows:
// Setup
function phoneticLookup(val) {
var result = "";
// Only change code below this line
switch(val) {
case "alpha":
result = "Adams";
break;
case "bravo":
result = "Boston";
break;
case "charlie":
result = "Chicago";
break;
case "delta":
result = "Denver";
break;
case "echo":
result = "Easy";
break;
case "foxtrot":
result = "Frank";
}
// Only change code above this line
return result;
}
// Change this value to test
phoneticLookup("charlie");
and it wants me to work out a way to look up any of the objects. I'm sure it's not a hard code, but I don't understand the explanation they give and no matter what I do, it still doesn't work and will come up with an 'Expected an assignment or function call and instead saw an expression' which is really annoying. I am not allowed to use switch, case or if statements. Pls help.
You will want to covert the switch statement into an object:
lookup = {
alpha: 'Adams',
bravo: 'Boston',
charlie: 'Chicago',
delta: 'Denver',
echo: 'Easy',
foxtrot: 'Frank'
};
Now that you have an object with keys and values you can get a values by using the key like this:
lookup['charlie'] //which will = 'Chicago'
lookup['echo'] //which will = 'Easy'
Since the key will be passed into the function as val you can now use the val to get the correct values associated with the key passed in.
return lookup[val]