Detecting Properties in JavaScript

In JavaScript we can add a property to an object at any point in code. It is encouraged to check whether a property exist 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.

  1. if(person.name){    
  2.    // code    
  3. }    
  4.     
  5. if(person.age){    
  6.    // code    
  7. }   

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 condition is either empty string, false, NaN, null, undefined or 0. There are chances that a property inside an object can contain a value which 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 a 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 exist or not before doing some operation using that particular property. To check if a property exist 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.

  1. var person={    
  2.    name:"pixxstudios",    
  3.    age:21,    
  4.    SayHello:function(){    
  5.       console.log("Hello");    
  6.    }    
  7. };    
For the above created object we can check if the properties exit or not using the ‘in’ operator.
  1. console.log("name" in person); // true    
  2. console.log("age" in person); // true    
  3. console.log("occupation" in person); // false    
  4. console.log("SayHello" in person); // true   
In the above code in last line we have checked a method existence using the ‘in’ operator; it won’t give any error since methods are also properties which are referencing some function. 
Ebook Download
View all
Learn
View all