Friday, 17 September 2010

JavaScript 'if' shorthand

I'm not generally a fan of shorthand but the code I'm working on at the minute has loads and loads of if... else statements and they're making the code look bloody ugly so I thought I'd look at the shorthand for if... else. Turns out that it involves a ternary operator.

Anyway the code I'm working on looks like this:

if($('#reverse').attr('checked')){
  newColour = red;
}else{
  newColour = red;
}

Which becomes:

newColour = $('#reverse').attr('checked') ? red : green;

One line instead of five is a big improvement. And it works like this: condition ? result1 : result2;