Web Development with jQuery®

(Elliott) #1

Programming Conventions (^) ❘ 23
break;
default:
condition = 'those';
}
Note in the preceding that no break statement appears in the default case. As the default, a break is
implied, and it is not necessary to include the break statement. I tend to deviate from the norm with
how I prefer switch control structures to be written.
switch (variable)
{
case 1 :
{
condition = 'this';
break;
};
case 2 :
{
condition = 'that';
break;
};
default:
{
condition = 'those';
};
}
I like to add curly braces around each case in the switch statement; I do this because I believe it
makes the switch statement easier to read and fl ow better to my eyes; however, ultimately, these
are not necessary. Concerning optional curly braces, I always include them, even if they’re techni-
cally optional. The same goes for semicolons. Terminating each line with a semicolon is technically
optional in JavaScript, although there are some circumstances in which you won’t be able to omit
it. I include all optional semicolons and curly braces, as I think that this not only makes the code
cleaner, more organized, and consistent, but also gives you a technical benefi t. If you want to com-
press your code to remove all additional white space, comments, and so on, these optional bits sud-
denly are no longer optional, but needed to keep the program functional after it’s been compressed.
In the following example, you can see what I mean by optional components:
if (condition)
something = 1
else if (another)
something = 2
else
something = 3
In JavaScript, the preceding code is perfectly valid. The semicolon is implied where there is a line
break. And as long as there is only a single statement being executed, technically you don’t have to
include curly braces. However, the above fails when it is compressed:
if (condition) something = 1 else if (another) something = 2 else something = 3
http://www.it-ebooks.info

Free download pdf