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")returnsfalse. - The property exists but has a value of
undefined→hasOwnProperty("key")returnstrue.
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"));
// trueChallenge
EasyCreate a function called toggleBookStatus that takes a book object as a parameter. The function should:
- If the book has a property
isReadthat is true, change it to false - If the book has a property
isReadthat is false, change it to true - If the book doesn't have an
isReadproperty, add it and set it to true - 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")); // trueTry it yourself
function toggleBookStatus(book) {
// Write your code here
}
// Do not write anything outside functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys