Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a object is defined, best practice.

Tags:

javascript

I have the following JSON response from a ajax-request.

var json = {
    "response": {
        "freeOfChargeProduct": {  
        "description": "Product",  
        "orderQty": 5,
        "productName": "XYZ",
        "qty": 6,
        "details": {
            "price": 55.5, 
            "instock": "true",
            "focQuantity": 1
        }
    }, 
    "orderLineId": 4788,
    "totalOrderLinePrice": "741.36",
    "totalOrderPrice": "1,314.92",
    "totalQty": 17
};

The JSON dosen't always return a "freeOfChargeProduct" property. So if I want to get the "freeOfChargeProduct" price, then I have to do the following:

var getFreeOfChargeProductPrice = function() { 
   var r = json.response;
   if (r && r.freeOfChargeProduct && r.freeOfChargeProduct.details) {
      return r.freeOfChargeProduct.details.price;         
   }
   return null;
};

No problems. But it's very annoying to check every property in the object, so I created a function that check if a property in a object is defined.

var getValue = function (str, context) {
    var scope = context || window,
        properties = str.split('.'), i;
    for(i = 0; i < properties.length; i++) {
      if (!scope[properties[i]]) {                       
         return null;
      } 
      scope = scope[properties[i]];        
    }
    return scope;
};

var price = getValue('json.response.freeOfChargeProduct.details.price');
// Price is null if no such object exists.

Now to my question: Is this a good or bad way to check if a property exists in an object? Any better suggestions/methods?

EDIT:

I don't wan't to use the &&-operator. I am lazy and I'm looking for a reusable method to check if a object (or property of a object) is defined.

:) Thanks!

like image 499
nekman Avatar asked Oct 17 '10 18:10

nekman


People also ask

How do you check if an object is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

Why is checking for null a good practice JavaScript?

As shown above, null is only loosely equal to itself and undefined , not to the other falsy values shown. This can be useful for checking for the absence of value — null and undefined both indicate an absence of value, thus they are loosely equal (they have the same value even though they are different types).

How can you tell if a object is typeof?

typeof null evaluates to 'object' , thus the correct way to use typeof to detect an object is typeof object === 'object' && object !== null . instanceof operator let's identify the instance's constructor. object instanceof Constructor evaluates to true if object is an instance of Constructor .


2 Answers

Use the guard pattern:

if (json.response && json.response.freeOfChargeProduct && json.response.freeOfChargeProduct.details) {
    // you can safely access the price
}  

This is how the guard pattern works.

if (a && a.b && a.b.c) { ... } else { ... }

The first check is "Does the property a exist?". If not, the else-branch gets executed. If yes, then the next check occurs, which is "Does object a contain the property b?". If no, the else-branch executes. If yes, the final check occurs: "Does the object a.b contain the property c?". If no, the else-branch executes. If yes (and only then), the if-branch executes.

Update: Why is it called "guard pattern"?

var value = a && b;  

In this example, the member b (the right operand) is guarded by the && operator. Only if the member a (the left operand) is truthy ("worthy"), only then the member b is returned. If, however, the member a is falsy ("not worthy"), then it itself is returned.

BTW, members are falsy if they return these values: null, undefined, 0, "", false, NaN. Members are truthy in all other cases.

like image 105
Šime Vidas Avatar answered Sep 30 '22 06:09

Šime Vidas


if(x && typeof x.y != 'undefined') {
    ...
}

// or better
function isDefined(x) {
    var undefined;
    return x !== undefined;
}

if(x && isDefined(x.y)) {
    ...
}

This will work for any data type in JavaScript, even a number that is zero. If you are checking for an object or string, just use x && x.y within the if statement, or if you already know that x is an object, if(x.y) ...

like image 29
PleaseStand Avatar answered Sep 30 '22 07:09

PleaseStand