Start learning free

LESSON 127 OF 671 · DICTIONARIES

Reading a Key That May Be Missing in JavaScript

Lesson Read the full explanation

TL ; DR:

Start with the default. Then an if with in replaces it with the value, when the key is there.


const points = {"Ana": 7};

let score = 0;
if ("Ben" in points) {
    score = points["Ben"];
}
console.log(score);   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] doesn't stop the program. It gives undefined, not 0.

Then points["Ben"] + 1 is NaN, "not a number".

So start score at the default. The if changes it only when "Ben" is a key.

Reading this way doesn't add the key. points still has one key afterwards.

With "Ana", the same code gives 7.


Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Declare plums at 0. Then use an if with in to read stock["plums"] when the key is there.

Then log the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · DICTIONARIES

    Dictionary Default Value in JavaScript, explained

    Missing often means none yet

    In many programs a missing key means "none yet". A shop with no plums has 0 plums. The lesson's data is an object that counts the fruit:

    const stock = {"apples": 5, "pears": 2};
    

    There is no "plums" key. Reading it does not stop the program, and it does not give 0 either:

    console.log(stock["plums"]);
    console.log(stock["plums"] + 1);
    
    undefined
    NaN
    

    The value undefined plus 1 is NaN, "not a number". Once it enters your arithmetic, every result that touches it is NaN too.

    Start with the default

    The fix has two moves. First declare the variable with the default value. Then use an if with in to replace the default with the real value, but only when the key is there.

    const stock = {"apples": 5};
    
    let plums = 0;
    if ("plums" in stock) {
        plums = stock["plums"];
    }
    console.log(plums);
    
    0
    

    The key is missing, so the if does not run and plums keeps its 0. Run the same pattern for "apples" and it prints 5, because the key exists and the if replaces the default.

    Reading this way does not add anything to the object. After the code runs, stock still has exactly one key.

    Alternatives

    The operator ?? gives the right-hand side when the left is undefined (or null). So stock["plums"] ?? 0 is 0 here, and stock["apples"] ?? 0 is 5. It is a shorter way to say the same thing, and it keeps a stored 0 as 0. This lesson uses the longer if form to practise in.

    Avoid || for this. With const z = {"plums": 0}, the expression z["plums"] || 9 is 9, because 0 counts as false, while z["plums"] ?? 9 is 0.

    Why the order of the two moves matters

    The default has to come first because the if only sometimes runs. If the default were set after the if, it would overwrite the real value every time. Setting it before means the variable always has a sensible value, whichever way the check goes, and the code that follows never has to wonder whether it is looking at a number or at undefined.

    The same shape works for any default, not only 0. A missing name might default to an empty string, and a missing list of items might default to an empty array. Pick the value that means "nothing yet" for the kind of data you have.

    The lesson's task

    The code already reads and prints the pears. The job is to do the same for plums, which are missing, without getting undefined:

    1. Declare plums with let, starting at the default, 0.
    2. Write an if that checks whether "plums" is a key of stock with in, and inside it set plums to stock["plums"].
    3. After the if, log the plums line, copying the pears line with plums in place of pears.
    const stock = {"apples": 5, "pears": 2};
    
    let pears = stock["pears"];
    console.log("We have " + pears + " pears");
    
    let plums = 0;
    if ("plums" in stock) {
        plums = stock["plums"];
    }
    console.log("We have " + plums + " plums");
    
    We have 2 pears
    We have 0 plums
    

    Common mistakes

    • Reading without checking. let plums = stock["plums"] gives undefined, and the line prints "We have undefined plums".
    • Declaring the default inside the if. A variable declared with let inside the braces exists only there, so the log after the if cannot see it.
    • Forgetting the default. Without the 0, the variable is undefined whenever the key is missing.

    Key takeaways

    • A missing key reads as undefined, not as 0.
    • Set the default first, then let an if with in replace it when the key exists.
    • Reading a key never adds it.
    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free