SmurfEkko SmurfEkko - 3 months ago 10
Javascript Question

Short hand if statement in JavaScript

I've seen this question a few times, I've also seen the Ternary operator suggested and used.

I was wondering how I use the Ternary operator in my example and if it's the best way.

My if statement :

if (dateSel.stock_qty <= 20) {
$(".stock_left").css("display", "block");
} else if (dateSel.stock_qty == 0) {
// do nothing
}


I changed this to :

dateSel.stock_qty <= (20) ? "Y" : "N";


What does the
Y
and
N
refer to. Can I place functions within the quotes?

For this type of if statement, is a Ternary the shortest way to handle it or is there a better way.

Answer

Ternary isn't going to shorten the things there, since it needs the second part anyway, unlike regular if conditions. Also, ternary wasn't really designed for these purposes, see Stack Overflow docs.

Go with this, just remove the else block and the brackets:

if(dateSel.stock_qty <= 20)$(".stock_left").css("display", "block");