Reputation: 32808
I have the following:
var viewID = $(link).data('dialog-id')
This works when there is a dialog-id value. But when there is no value then viewID gets the value of "undefined".
Is there a way that I can make the value of viewID be equal to an empty string if dialog-id is not available or be equal to dialog-id if it is available?
Upvotes: 1
Views: 108
Reputation: 754743
The easiest way is to use the ||
operator
var viewID = $(link).data('dialog-id') || '';
The '||' operator takes a value on the left and right. If the value on the left is truthy then it will be returned else the right value will be. The value undefined
is falsy hence if it's returned from the data('dialog-id')
call then it will pick ''
instead
Upvotes: 0
Reputation: 3725
var viewID = $(link).data('dialog-id') == undefined ? "" : $(link).data('dialog-id');
Upvotes: 3
Reputation: 623
Alternately:
var viewID = $(link).data('dialog-id')
if (viewID == null) {
viewID = '';
}
This also works, since undefined
and null
are considered equal.
Upvotes: 0
Reputation: 488424
You can do:
var viewID = $(link).data('dialog-id') || '';
Which works thanks to the way Javascript handles short-circuit evaluation.
Upvotes: 6