tags:

views:

59

answers:

3
var fmt = document.documentElement.clientWidth;
        var cls = (fmt<=240)?'pda_ver':(fmt>240&&fmt<=320)?'pda_hor':(fmt>320&&fmt<=640)?'screen_ultralow':(fmt>640&&fmt<=800)?'screen_low':(fmt>800&&fmt<=1024)?'screen_med':(fmt>1024&&fmt<=1280)?'screen_high':'screen_wide';

can someone tell me what this does (just the part where the variable is set with a value. I do not understand... what are the ?, : have for a role here)? i have never seen a variable declared like that. Is this a conditional variable setting? if yes how does it work ?

working example

+10  A: 

This is a horrible example of abuse of the ternary operator.

Using a switch statement would look much nicer.

Pekka
If you ever have more than 1 ? in a line of code, think about it some more ;)
bwawok
what is horrible about this example?
meo
Really ugly indeed
baloo
@meo just that it's extremely bad to read and modify.
Pekka
@meo: The fact that you, among other people, can't immediately read it.
Matti Virkkunen
@meo It's a very nested use and consequently very difficult to read.
Fletcher Moore
but is there a practical reason to do this beside writing less code? is it faster then the classical if statement somehow?
meo
@meo no, it's just convenient sometimes. But easy to abuse
baloo
+4  A: 

This construction is somewhat common in languages:

statement3 ? statement2 : statement1

It is used to inline a conditional, and it reads:

if (statement3) {
  statement2;
} else {
  statement1;
}
Fletcher Moore
+1  A: 

It's a shorthand of:

var cls;
if (fmt <= 240) {
  cls = 'pda_ver';
} else {
 if (fmt > 240 && fmt <= 320) {
   cls = 'pda_hor';
 } else {
 ....

and so on

baloo
"Shorthand" is arguable... I'd choose if/ else over that mess any day :)
Matt