Start learning free

LESSON 126 OF 671 · DICTIONARIES

Checking for a Key in JavaScript

Lesson

TL ; DR:

Write key in obj to ask whether an object has a key. The answer is true or false, so it goes in an if.


const capitals = {"France": "Paris", "Japan": "Tokyo"};

if ("Japan" in capitals) {
    console.log(capitals["Japan"]);   // Tokyo
}

if (!("Spain" in capitals)) {
    console.log("No Spain");          // No Spain
}


Full lesson:

Reading a missing key doesn't stop the program. capitals["Spain"] just gives undefined.

That undefined can travel far before something breaks. So check first.

"Spain" in capitals is true when "Spain" is a key. It is false when it isn't.

For the opposite, put ! before the whole check, in parentheses. Without them, ! applies to "Spain" alone, and the check is always false.

Don't check with if (capitals["Spain"]). A key whose value is "" or 0 would look missing.

A value is not a key

in looks only at the keys. "Paris" in capitals is false, because "Paris" is a value.

A key must match exactly, upper and lower case too. "japan" in capitals is false.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, log Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with ! and in. If so, log cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check