1

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?

4 Answers 4

6

You can do:

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Alternately:

var viewID = $(link).data('dialog-id')
if (viewID == null) {
    viewID = '';
}

This also works, since undefined and null are considered equal.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.