简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM