Quiz Time, JavaScript Through the Ages Edition
Update 2020-04-15: This one was solved by Todd Sprinkel (of Sponge.io)! I explain the answer in a follow-up post.
Feels like bribery quiz time! I’ll send a $25.00 Seamless gift card — and make a matching grant to Food Bank NYC — to the first person who correctly answers this JS challenge.
The setup
Your website supports any browser that has a native Object.keys
function, and you’re writing some basic JS.
The challenge
Why is code snippet #1 a wrong way to get the number of apples, while snippet #2 is one of the right ways?
#1: A Wrong Way
var fruitBasket = {
apples : 24,
oranges : 9,
pears : 12
};
var fruitNames = Object.keys(fruitBasket),
fruitCounts = Object.keys(fruitBasket).map(function(fruitName){
return fruitBasket[fruitName];
});
var applesCount = fruitCounts[fruitNames.indexOf("apples")];
#2: A Right Way
var fruitBasket = {
apples : 24,
oranges : 9,
pears : 12
};
var fruitNames = Object.keys(fruitBasket),
fruitCounts = fruitNames.map(function(fruitName){
return fruitBasket[fruitName];
});
var applesCount = fruitCounts[fruitNames.indexOf("apples")];
Clues and anti-clues
- It’s not merely about repetition or code style or verbosity.
- It’s an actual (dys)functional bug, depending on... certain things.
- It’s not about other potential inputs into the same code — but literally about the exact code you see here.
- Yes, you could use
fruitBasket.apples
orfruitBasket["apples"]
. But this isn’t about simpler and more obvious ways to do it, it’s about wrong results vs. right results.