Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I set a javascript variable to "" if it is undefined?

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

Answers (4)

JaredPar
JaredPar

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

Hungry Beast
Hungry Beast

Reputation: 3725

var viewID = $(link).data('dialog-id') == undefined ? "" : $(link).data('dialog-id');

Upvotes: 3

Feysal
Feysal

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

Paolo Bergantino
Paolo Bergantino

Reputation: 488424

You can do:

var viewID = $(link).data('dialog-id') || '';

Which works thanks to the way Javascript handles short-circuit evaluation.

Upvotes: 6

Related Questions