Menu
Coddy logo textTech

Check If Key Exists

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 16 of 65.

To check for a specific key in a JSON object, use either the in operator or hasOwnProperty(). For example:

const product = { "name": "Laptop", "price": 900 };
if ("price" in product) {
  console.log("Key exists!");
}

if (product.hasOwnProperty("price")) {
  console.log("Key exists!");
}

This is handy when verifying if certain data is present before processing.

obj.hasOwnProperty("key") will return false if obj does not have key as its own property. However obj.key === undefined does not necessarily mean hasOwnProperty("key") will return false. There are two cases where obj.key is undefined:

  • The property does not exist at all → hasOwnProperty("key") returns false.
  • The property exists but has a value of undefinedhasOwnProperty("key") returns true.

For example:

const obj1 = {};  
console.log(obj1.key); // undefined
console.log(obj1.hasOwnProperty("key"));
// false

const obj2 = { key: undefined };
console.log(obj2.key); // undefined
console.log(obj2.hasOwnProperty("key"));
// true
challenge icon

Challenge

Easy

Create a function called toggleBookStatus that takes a book object as a parameter. The function should:

  1. If the book has a property isRead that is true, change it to false
  2. If the book has a property isRead that is false, change it to true
  3. If the book doesn't have an isRead property, add it and set it to true
  4. Return the modified book object

Cheat sheet

To check for a specific key in a JSON object, use the in operator or hasOwnProperty():

const product = { "name": "Laptop", "price": 900 };

// Using 'in' operator
if ("price" in product) {
  console.log("Key exists!");
}

// Using hasOwnProperty()
if (product.hasOwnProperty("price")) {
  console.log("Key exists!");
}

hasOwnProperty() returns true if the property exists (even if its value is undefined), and false if the property doesn't exist:

const obj1 = {};  
console.log(obj1.hasOwnProperty("key")); // false

const obj2 = { key: undefined };
console.log(obj2.hasOwnProperty("key")); // true

Try it yourself

function toggleBookStatus(book) {
    // Write your code here
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow