Home > Web Front-end > JS Tutorial > body text

How to Check for Object Property Existence Using a Variable in JavaScript?

DDD
Release: 2024-10-31 18:35:29
Original
888 people have browsed it

How to Check for Object Property Existence Using a Variable in JavaScript?

Checking Object Property Existence with a Variable

In JavaScript, verifying the presence of an object property using a variable can be a common task. However, directly using the variable as the property name leads to undefined results.

Example:

<code class="js">var myObj;
myObj.prop = "exists";
var myProp = "p" + "r" + "o" + "p";

if (myObj.myProp) {
  alert("yes, i have that property");
};  // Undefined</code>
Copy after login

To overcome this, one must utilize methods that explicitly check property existence.

Solutions:

Option 1: hasOwnProperty

<code class="js">var myProp = 'prop';
if (myObj.hasOwnProperty(myProp)) {
  alert("yes, i have that property");
}</code>
Copy after login

Option 2: in operator (checks for both direct and inherited properties)

<code class="js">var myProp = 'prop';
if (myProp in myObj) {
  alert("yes, i have that property");
}</code>
Copy after login

Option 3: Direct in operator usage (checks only for direct properties)

<code class="js">if ('prop' in myObj) {
  alert("yes, i have that property");
}</code>
Copy after login

Note: hasOwnProperty does not check inherited properties, while the in operator does.

The above is the detailed content of How to Check for Object Property Existence Using a Variable in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!