PDA

View Full Version : conditions without brackets



ggalan
01-21-2011, 03:39 AM
ive seen code written like this


if(jQuery.support.opacity)
$('div.box-5').find('div.movebox-content *').fadeTo(200, 1);
else
$('div.box-5').find('div.movebox-content *').css("visibility","visible");
$(document).trigger("newBackground",[nI]);


shouldnt it be like this?


if(jQuery.support.opacity){
$('div.box-5').find('div.movebox-content *').fadeTo(200, 1);
}else{
$('div.box-5').find('div.movebox-content *').css("visibility","visible");
$(document).trigger("newBackground",[nI]);
}


but obviously it works without the brackets, can anyone tell me whats going on?

jscheuer1
01-21-2011, 05:10 AM
To be technically perfect, javascript like HTML needs to follow certain syntax rules. However, browsers will error correct for a lot.

These technicalities become increasingly important if one wants to compress and/or encrypt ones code. And if code is being imported via the responseText or responseXML of an AJAX or other server request.

In your example though the two versions are not equivalent. If brackets are omitted, only the immediately following directive is a part of the conditional. So


if(jQuery.support.opacity)
$('div.box-5').find('div.movebox-content *').fadeTo(200, 1);
else
$('div.box-5').find('div.movebox-content *').css("visibility","visible");
$(document).trigger("newBackground",[nI]);

is equivalent to:


if(jQuery.support.opacity){
$('div.box-5').find('div.movebox-content *').fadeTo(200, 1);
} else {
$('div.box-5').find('div.movebox-content *').css("visibility","visible");
}
$(document).trigger("newBackground",[nI]);

djr33
01-21-2011, 07:10 AM
The braces {} group line(s) as a unit. This means that you can group 2 or more lines as, effectively, a single line (or a single "operation").

if (condition) function();

That's perfectly fine, because if (condition) RESULT. But to make RESULT complex, or span multiple lines, the braces allow for something other than just the default one line item.