saawsann
saawsann

Reputation: 685

Shorthand syntax to check a variable in JS?

Let's say we want to check if a variable is correctly set (not undefined, not empty, not false...) before using it:

var myVar = getData();
if(myVar) {
    doSomething(myVar);
}

We could shorten the code by not declaring myVar. But, in this case, getData() is called twice, not ideal.

if(getData()) doSomething(getData());

Is there any other alternative to keep this code short but somehow clean?

Upvotes: 0

Views: 43

Answers (1)

Bergi
Bergi

Reputation: 664433

You don't really get around that variable. Of course, you can also do

var myVar = getData();
if (myVar) doSomething(myVar);

or even

var myVar;
if (myVar = getData()) doSomething(myVar);

but it basically won't get better than that.

If you want to avoid introducing a variable in your scope, you can work around it by using a helper function - also if you find yourself doing this over and over:

function maybeDo(val, action) {
    if (val) return action(val);
}
maybeDo(getData(), doSomething);

Upvotes: 1

Related Questions