Jacksonkr
Jacksonkr

Reputation: 32247

Shorter-hand ternary logic

Is there a shorter way to use ternary logic in js when the else is "null"?

true ? console.log(true) :0; // current

I'm looking for something like

true ? console.log(true);
//or
true ?: console.log(true);

Just curious. Thanks!

Upvotes: 3

Views: 430

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

Try this:

true && console.log(true);

This works because the && makes this expression into a boolean. JavaScript will try to evaluate it. If the first value is false, nothing happens because of short-circuiting. If it's true, then it evaluates the second (the console.log).

You can also use the || as a quick way to do empty in JavaScript (beware of falsey values like 0 and '').

var a = false;
var b = a || 6; // b will be 6

Upvotes: 6

Related Questions