Start learning free

LESSON 133 OF 289 · DICTIONARIES - CHALLENGES

Safe Lookup in TypeScript: Checking a Key with in

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

    TYPESCRIPT · DICTIONARIES - CHALLENGES

    Safe Lookup in TypeScript, explained

    Problem overview

    The method safeLookup receives scores, an object used as a dictionary from names to scores, and a name. It returns the score of that name, or 0 when the name is not a key of the object.

    With {"Ana": 90, "Ben": 75, "Cara": 88} and "Ben", the answer is 75. With "Dan", who is not in the object, the answer is 0. An empty object has no keys, so every name gives 0. Names must match exactly: "ana" is not "Ana".

    Approach

    Reading a key that does not exist is not an error in JavaScript and TypeScript. scores["Dan"] quietly gives undefined, so returning it directly would break the promise of a number. The method needs to ask first whether the key is there.

    The in operator does that: name in scores is true when scores has a key spelled like the value of name. The method uses it in an if. When the key exists it returns the stored score and ends. Otherwise it falls through to a final return 0.

    Step by step

    1. Test the key. Write an if with the condition name in scores, and inside it return scores[name]. The brackets use the variable's value as the key.
    2. Return 0 after the if. This line is reached only when the condition was false, because a return inside the if has already ended the method.

    The solution in TypeScript

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

    Details worth knowing:

    • The key goes on the left of in. name in scores checks keys. It never checks values, so it is not like asking whether an array contains a value.
    • A score of 0 is still a key. With {"Ana": 0}, "Ana" in scores is true and the method returns 0 from the first branch. Writing scores[name] || 99 instead would give 99 for that entry, because 0 is falsy. The ?? operator only replaces undefined and null, so scores[name] ?? 0 is another correct way to write the method in one line.
    • in also sees inherited names. Every object inherits properties such as toString, so "toString" in scores is true even for {}, and safeLookup({}, "toString") returns a function. A name like that is not a real key. To count only the object's own keys, use Object.hasOwn(scores, name). It gives false for "toString" and true for "Ana" in {"Ana": 0}. For ordinary names like the ones in this lesson, in is enough.
    • Types are erased. The number return type is not checked at run time.

    Complexity

    Time: O(1) on average. The membership test and the read are each a single lookup.

    Space: O(1). Nothing new is allocated.

    Edge cases and common mistakes

    • Empty object. {} has no keys, so the method returns 0.
    • Different case. "ana" is not a key of {"Ana": 90}, so the answer is 0.
    • Returning the lookup directly. return scores[name] gives undefined for a missing name, where the answer must be 0.
    • Treating 0 as missing. A real score of 0 must come back as 0 through the stored value. Testing the value for truthiness instead of testing the key can hide that.
    • Swapping the operands. scores in name is a type error, and it throws a TypeError at run time because name is a string, not an object.

    Testing

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