I am using jQuery 1.7.1
I am just starting to use the JavaScript ternary operator to replace simple if/else statements. I have done so successfully in several places. I was surprised when I successfully made something else work when I thought for sure it wouldn't, but I tried anyway.
Here's the original statement:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
if (IsChecked == true){
removeItem($this);
} else {
addItem($this);
}
}
Here's the same function using the ternary operator:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
(IsChecked == true) ? removeItem($this) : addItem($this);
}
I was surprised because all of the examples I saw being used were merely setting variables like this:
x = (1 < 2) ? true : false;
My question is whether this is "normal" use and will it work in most versions of JavaScript? Where will it fail? Are there other less obvious uses for it?
UPDATE -- Thanks for the "real world" advice!!!
I am using this as my function:
function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}
(IsChecked ? removeItem : addItem)($this). However, to answer your question, yes this is normal and there is nothing wrong with using ternary operators as long as they don't detract from maintainability or readability in a situation where that is needed. jsfiddle.net/vsB3fif($this.hasClass("IsChecked")) removeItem($this); else addItem($this)is the proper way. The ternary operator is not meant for cases like this but for things likefoo(isChecked ? 'bar' : meow());(i.e. when you care about the "return value" of whatever you do in the then/else blocks)$(this).hasClass("IsChecked") ? removeItem($this) : addItem($this);I can understand your code as-is on one line, so it fits my rule of thumb (see post below). Works for me.