Start learning free

LESSON 131 OF 671 · DICTIONARIES - CHALLENGES

Safe Lookup in JavaScript: The in Operator and a Default

Practice Read the full explanation

Given a dictionary scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · DICTIONARIES - CHALLENGES

    Safe Lookup in JavaScript, explained

    Problem overview

    The method safeLookup receives scores, an object from names to scores, and a name. It returns the name's score, or 0 when name isn't a key of scores.

    With scores = {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. An empty object has no keys, so every name gives 0. Spelling counts: "ana" is not the key "Ana", so it also gives 0.

    Approach: check first, then read

    Reading a missing key from an object doesn't fail. It gives undefined. With the scores above, scores["Dan"] is undefined, and returning that would break the lesson, which wants 0.

    The fix is to ask whether the key exists before reading it. The in operator does that: name in scores is true when scores has a key spelled like the value of name, and false otherwise. If the answer is yes, return the stored score. Otherwise fall through to a default of 0.

    Two other idioms give a default as well: scores[name] ?? 0 uses the right side when the left side is undefined or null, and Object.hasOwn(scores, name) asks the same yes or no question as in. The lesson uses the explicit if with in so each decision is visible in the code.

    Step by step

    1. Write the check. An if with the condition name in scores. Inside it, return scores[name]. Brackets are needed because name is a variable.
    2. Return the default. After the if's closing brace, return 0. Code only gets there when the key is missing, because a return inside the if has already ended the method otherwise.

    The solution in JavaScript

    class Solution {
        safeLookup(scores, name) {
            if (name in scores) {
                return scores[name];
            }
            return 0;
        }
    }
    

    Details worth knowing:

    • The order of operands in in. The key goes on the left and the object on the right. name in scores asks about keys. It doesn't search the values.
    • No else is needed. A return leaves the method immediately, so the final return 0 only runs when the if didn't.
    • Inherited keys. The in operator also reports properties an object inherits. For an empty object {}, "toString" in {} is true, so safeLookup({}, "toString") returns the function toString instead of 0. The lesson's names are plain words of letters that never collide with such built-in names in practice, but remember it when keys come from users. Object.hasOwn(scores, name) checks only the object's own keys.
    • A score of 0. A key can exist with the value 0. Because the solution checks for the key and not for a truthy value, {"Ana": 0} returns its stored 0, which happens to look the same as the default.

    Edge cases and common mistakes

    • An empty object. {} with "Ana" returns 0, because "Ana" in {} is false.
    • Different case. "ana" against the key "Ana" gives 0: keys are compared exactly.
    • Skipping the check. return scores[name] alone works for names that exist, but returns undefined for the others.
    • Testing the value instead of the key. if (scores[name]) treats a stored score of 0 as missing. Here it still returns the right number, but the check says the wrong thing, and it breaks for any default other than 0.
    • Returning inside the if only. Without the final return 0, the method returns undefined for missing names.

    Testing

    • {"Ana": 90, "Ben": 75, "Cara": 88} with "Ben" gives 75.
    • The same object with "Dan" gives 0.
    • {} with "Ana" gives 0.
    • The same three-name object with "ana" gives 0.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free