Check if a Key Exists in an Object in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to check if a key exists in an object. In JavaScript, we can achieve this by using Object.hasOwn() method.

Example

let user = {
    name: "ScanSkill",
    roll: "1",
    addressOne: "Kathmandu"
}

console.log("Does addressOne exist in user: ", Object.hasOwn(user, "addressOne"));

console.log("Does addressTwo exist in user: ", Object.hasOwn(user, "addressTwo"));

Here, we can see that Object.hasOwn() method takes two parameters first being the user object and the second one the addressOne key. It returns boolean value.

Output
Does addressOne exist in user: true
Does addressTwo exist in user: false