Thursday, 30 August 2018

JavaScript: hasOwnProperty(): Check whether object has given property (or) not

In previous post, I explained how to test for the property of an object using 'in' operator. JavaScript also provides
hasOwnProperty() method to test, whether an object owns given property (or) not.

Syntax
object.hasOwnProperty(propertyName)

Above method return true, if the object has given property, else false.

properties.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        var employee = {
            firstName: "Hari Krishna",
            age: 26
        };

        document.write("employee.hasOwnProperty(\"firstName\") : " + employee.hasOwnProperty("firstName") + "<br />");
        document.write("employee.hasOwnProperty(\"age\") : " + employee.hasOwnProperty("age") + "<br />");
        document.write("employee.hasOwnProperty(\"lastName\") : " + employee.hasOwnProperty("lastName") + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

employee.hasOwnProperty("firstName") : true
employee.hasOwnProperty("age") : true
employee.hasOwnProperty("lastName") : false


Previous                                                 Next                                                 Home

No comments:

Post a Comment