I have the following JSON response from a ajax-request.
var json = {
\"response\": {
\"freeOfChargeProduct\": {
\"description\": \"Prod
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.