loader

Loading

CoderrShyam logo

CoderrShyam

  • Home
  • About
  • Contact
  • Blog
  • Tutorials
    LoginSignup

How to Check if Keys Exist in JavaScript Objects

Learn how to check if a key exists in a JavaScript object.

Back

Sometimes you need to check whether a specific key exists in a JavaScript object. This article explores two popular methods to achieve that:

  1. Using the 'in' Operator
  2. Using the hasOwnProperty() Method

Method 1: Using the in Operator

The in operator returns true if the specified property exists in the object or its prototype chain, otherwise false.

Syntax

if (key in object) {
  // your code
}

Example

main.js
const person = { name: "John", age: 30 };

if ("name" in person) {
  console.log("Name exists in person object");
} else {
  console.log("Name does not exist in person object");
}

Note

The 'in' operator checks the entire prototype chain, not just the object's own properties.

Method 2: Using hasOwnProperty()

The hasOwnProperty() method returns true if the specified property exists directly on the object (not inherited). This is often a safer choice when you only care about the object's own properties.

Syntax

object.hasOwnProperty(propertyName); 

Example

main.js
const person = { name: "John", age: 30 };

if (person.hasOwnProperty("name")) {
  console.log("Name exists in person object");
} else {
  console.log("Name does not exist in person object");
}

Conclusion

Both the in operator and the hasOwnProperty() method are valuable tools in JavaScript:

  • Use the in operator if you want to check for a property in the object or anywhere in its prototype chain.
  • Use hasOwnProperty() if you need to check only for the object's own properties.

Happy coding!

Written by

Shyam Verma

At

October 12th, 2024

March 7th, 2026

Read time

2 min

Tags

javascriptobjectskeyshasOwnPropertyin-operator
Follow us on GitHub
CoderrShyam logo

CoderrShyam

A professional web developer.

GithubTwitterBlue Sky

Resources

HomeAboutBlogContactTutorials

Socials

GitHubTwitterInstagramLinkedInFacebookThreadsBlue SkyStack OverflowReddit

Legal

Privacy PolicyTerms of Service

Authentication

ProfileLoginSignupForgot Password

© 2026CoderrShyamAll Rights Reserved.

CoderrShyam

Leave comment