Introduction
In JavaScript we can add a property to an object at any point in code. It is encouraged to check whether a property exists or not before doing some operation using that particular property. To check if a property exists or not there are several methods provided in JavaScript which we will check one by one.
The first method which is often used by most of the JavaScript developers is checking for “object.propery” inside an if condition.
- if(person.name){
-
- }
-
- if(person.age){
-
- }
This method is not reliable; the reason being that if condition returns true if the conditional statement is either an object, a non-zero number, a non-empty string, or true and it returns false if the condition is either an empty string, false, NaN, null, undefined or 0. There are chances that property inside an object can contain a value that is executed to false by the if statement. For example, a person object can contain an age property with initial value as 0, but if statement will return false even the property exists.
So a better way of checking that property exists or not is by using the ‘in’ operator. What ‘in’ operator does is checks if a specific property exits for a given object and returns true or false accordingly.
In JavaScript we can add a property to an object at any point in code. It is encouraged to check whether a property exists or not before doing some operation using that particular property. To check if a property exists or not there are several methods provided in JavaScript which we will check one by one.
The first method which is often used by most of the JavaScript developers is checking for “object.propery” inside an if condition. Let us create a person object with few properties.
- var person={
- name:"pixxstudios",
- age:21,
- SayHello:function(){
- console.log("Hello");
- }
- };
For the above-created object we can check if the properties exist or not using the ‘in’ operator.
- console.log("name" in person);
- console.log("age" in person);
- console.log("occupation" in person);
- console.log("SayHello" in person);
In the above code in the last line we have checked a method existence using the ‘in’ operator; it won’t give any error since methods are also properties that are referencing some function.