I’ve found myself writing a lot of code similar to this:
$('.selector').addClass(condition ? 'class' : '');
I know this may be silly and whiny, but I was just curious if there was a way to do that without the false condition in Javascript. I’ve looked around and haven’t really found any operator that can do that, but I could be (and hope I am) wrong.
I’m not necessarily looking to optimize my code, this is just curiosity 🙂
Thanks.
JavaScript’s
&&operator short-circuits. You’ll see something like this used commonly in a number of scripts and libraries:Or as mgibsonbr’s comment states, you can simply
&&within the method itself:It’s much less intuitive, though, as it’s not a commonly-known fact that
a && bresults inbin JavaScript when both values are truthy, and nottrueunlike in other languages.