Wednesday, July 27, 2005

My Kickass Javascript ternary operator trick.

I'm sure someone else has done this before, but I just discovered it myself, and it's mine now. Mine all mine.

I was just in need of a somewhat lengthy if-else statement to assign a string a particular value based on a series of variables. It's for a browser sniffing script I'm using to tell if someone's browser needs to be updated before they use an online course.

Basically, i'm assigning the variable platform a value based on the value of a bunch of other variables:

if (is_win98==true)
   platform="win98";
else if( is_winme==true)
   platform="winME";
else if( is_winxp==true)
   platform="winXP";
else if( is_win2k==true)
   platform="win2k";
else
   platform = "";
So anyway I needed this longish if-else statement and I wondered if it could be done in 1 line using ternary operators strung together. To my utter surprise, this works just like the above...

platform = is_win?"win":is_winme?"winME":is_winxp?"winXP":is_win2k?"win2k":"";

So how cool is that? Pretty cool I think.

1 Comments:

Blogger weasel said...

yummmm, C++ like...

6:42 PM  

Post a Comment

<< Home