Check if a property exists in an JavaScript object

 Check if a property exists in an JavaScript object

In JavaScript, there is a method called as hasOwnProperty() to check if a property belongs to the mentioned object. 

It scans the entire object to find the property in question and returns a true or false value. If found, returns true, otherwise false.

Syntax:
obj.hasOwnProperty(property)

As you can see, when the code runs it returns true in the first instance as the property breed belongs to the object myDog. In the second instance, the legs property does not exist in myDog thus returns false.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check if a property exists in object</title>
</head>
<body>
    <div id="res"></div>
    <script>
        var res = document.getElementById("res");

        var myDog = {
            name: "Fido",
            age: 5,
            breed: "Pug",
            favFood: "Muffins"
        };
        
        var rval = myDog.hasOwnProperty("breed");
        res.innerText = rval;
        rval = myDog.hasOwnProperty("legs");
        res.innerHTML += "<br>" + rval;
    </script>
</body>
</html>

There are other ways of achieving the same result but they require manual intervention. You can check them here



Post a Comment

0 Comments

React