However, I am wondering what best practice is, when using a ternary operator, to append no elements
Best practice would be not to use a ternary operator for a situation where it's not appropriate. If you don't know what goes in the third operand, it's clear that the situation isn't a good fit for using a ternary operator.
While you can use a blank string:
$('<div>').append(
(myBooleanFlag ? '<p>Some child element</p>' : '')
);
...it's much clearer, just as concise, and more efficient to use the if
:
if (myBooleanFlag) {
$('<div>').append('<p>Some child element</p>');
}
I hesitate to mention it, but another JavaScript idiom that applies here is using the &&
operator and the expression statement:
myBooleanFlag && $('<div>').append('<p>Some child element</p>');
This is possible because in JavaScript, an expression can be a statement. Since &&
is short-circuited, if myBooleanFlag
is falsey, the append
call is not triggered.
Some people really love that syntax. Others find it hard to read and debug. It's basically a hidden if
in this form:
if (myBooleanFlag) $('<div>').append('<p>Some child element</p>');
...which falls afoul of all the usual coding convention things about always using {}
with conditionals, etc. But again, it's a style thing.
Side note: You can just use the string in the positive case above, no need to use $(...)
on it before passing it to append
, so I've left it out in the above.
Side note 2: There's no need to put parens around the conditional when passing it as an argument to a function.