Basic Data Structures - Check if an Object has a Property

I am not able to get it correctly done

1 Like

What have you tried so far, what’s your current code?

1 Like

I tested the code below and it works.

The Below Is From Google Search Generative AI and Is Experimental.
You may see inaccurate creative content.

There are three ways to check if an object has a property in JavaScript:

  1. Use the hasOwnProperty() method

The hasOwnProperty() method checks if an object has a property as its own property (as opposed to inheriting it).

const obj = {  
name: "John Doe",  
age: 30,};
// Check if the object has the "name" property
const hasName = obj.hasOwnProperty("name");
  1. Use the in operator

The in operator checks if an object has a property, regardless of whether it is a direct property or an inherited property.

const obj = {  
name: "John Doe",  
age: 30,};
// Check if the object has the "name" property
const hasName = "name" in obj;
  1. Use the === undefined operator

The === undefined operator checks if the value of a property is undefined. If it is, then the property does not exist.

const obj = {  
name: "John Doe",  
age: 30,};
// Check if the object has the "age" property
const hasAge = obj.age !== undefined;

Which method you use to check for a property depends on your specific needs.

2 Likes