Check If an Associative Array Key Exists with JavaScript | Plantpot

Check If an Associative Array Key Exists with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to check if an associative array key exists with JavaScript.

Check if an associative array key exists

First look at the code below.

const fruits = {
  apple: {
    color: "red",
    price: "$1"
  }
}

In this associative array, an object with color and price data is defined for the key apple.

So what happens if we call it like this:

fruits.orange.price //Uncaught TypeError: Cannot read property 'price' of undefined

We get an error because the key orange doesn't exist in the associative array.

To avoid these errors, it is safe to check if the key actually exists before proceeding.

Sponsored links

The simplest way to check if an associative array key exists is to use an if statement and the in operator.
If there is a key, true is returned, otherwise false is returned.

if (orange in fruits) {
 // do something
} else {
 // do something
}

The following methods are also available as conventional methods.

if (fruits.orange) {
  // do something
} else {
  // do something
}

However, empty strings and 0 are also judged as false.
Therefore, it is safer to use the if statement and the in operator.