I am using jQuery, Backbone (and underscore) and RequireJS.
I have this code:
var products = _.map(items, function(item) {
return new ProductModel({
title: item.product.title,
description: item.product.description,
link: item.product.link,
'image-src': item.product.images[0].link,
'image-height': item.product.images[0].height,
'image-width': item.product.images[0].width
});
});
Unfortunately, everything might be null. By everything I mean that item, item.product, item.product.images, item.product.images[0] and so on might be nulls.
I am looking for something like “coalesce” that:
- will know how to handle
nulls and will not throw exceptions foritem.productifitemisnull. - will allow me to provide a default value if there was a
null.
Is there anything like that?
You can use boolean
&&and rely on short-circuiting:More likely, you don’t want to perform the same test across so many lines. I would store your return value with its various attributes set to some sane default and then conditionally add the real values if your
item.product.images[0]is non-null: