Start learning free

LESSON 127 OF 671 · DICTIONARIES

Reading a Key That May Be Missing in JavaScript

Lesson

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