Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
65 views

Code Conventions For The Javascript Programming Language

The document provides coding conventions for JavaScript programming. It recommends declaring all variables at the top of functions, minimizing use of global variables, and formatting functions, statements, and control structures consistently. Comments should explain non-obvious code, but avoid redundant statements. Names, indentation, and line lengths are addressed. Overall it aims to improve readability and standardization of JavaScript code.

Uploaded by

lankepd
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Code Conventions For The Javascript Programming Language

The document provides coding conventions for JavaScript programming. It recommends declaring all variables at the top of functions, minimizing use of global variables, and formatting functions, statements, and control structures consistently. Comments should explain non-obvious code, but avoid redundant statements. Names, indentation, and line lengths are addressed. Overall it aims to improve readability and standardization of JavaScript code.

Uploaded by

lankepd
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

10/17/11 Code Conenion fo he JaaScip Pogamming Langage

1/8 jaacip.cockfod.com/code.hml
Code Conenion fo he JaaScip
Pogamming Langage
Thi i a e f cdig cei ad e f e i JaaSci gaig. I i iied b he S
dce Cde Cei f he Jaa Pgaig Lagage. I i heai dified f ce
becae JaaSci i Jaa.
The g-e ae f fae a gaiai i i diec i he ai f he cdebae.
Oe i ifeie, a ga i be haded b a ai f had ad ee. If a ga i abe
cea cicae i ce ad chaaceiic, i i e ie ha i i bea he dified i he
ee--dia fe.
Cde cei ca he i edcig he biee f ga.
A f JaaSci cde i e diec he bic. I hd aa be f bicai ai.
Neae c.
JaaScip File
JaaSci ga hd be ed i ad deieed a .js fie.
JaaSci cde hd be ebedded i HTML fie e he cde i ecific a ige ei.
Cde i HTML add igifica ageeigh ih i f iigai b cachig ad
cei.
<script src=fieae.js> ag hd be aced a ae i he bd a ibe. Thi edce he
effec f dea ied b ci adig he age ce. Thee i eed e he
language tpe aibe. I i he ee, he ci ag, ha deeie he MIME e.
Indenaion
The i f ideai i f ace. Ue f ab hd be aided becae (a f hi iig i he
21 Ce) hee i i a adad f he acee f ab. The e f ace ca dce a
age fieie, b he ie i igifica e ca e, ad he diffeece i eiiaed b
iificai.
Line Lengh
Aid ie ge ha 80 chaace. Whe a aee i fi a ige ie, i a be ecea
bea i. Pace he bea afe a ea, idea afe a ca. A bea afe a ea
deceae he ieihd ha a c-ae e i be aed b eic iei. The e ie
hd be ideed 8 ace.
Commen
10/17/11 Code Conenion fo he JaaScip Pogamming Langage
2/8 jaacip.cockfod.com/code.hml
Be generous with comments. It is useIul to leave inIormation that will be read at a later time by people
(possibly yourselI) who will need to understand what you have done. The comments should be well-
written and clear, just like the code they are annotating. An occasional nugget oI humor might be
appreciated. Frustrations and resentments will not.
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder
to read and understand.
Make comments meaningIul. Focus on what is not immediately visible. Don't waste the reader's time with
stuII like
i = 0; // Set i to zero.
Generally use line comments. Save block comments Ior Iormal documentation and Ior commenting out.
Vaiable Declaaion
All variables should be declared beIore used. JavaScript does not require this, but doing so makes the
program easier to read and makes it easier to detect undeclared variables that may become implied
globals. Implied global variables should never be used.
The var statements should be the Iirst statements in the Iunction body.
It is preIerred that each variable be given its own line and comment. They should be listed in alphabetical
order.
var currentEntry; // currently selected table entry
var level; // indentation level
var size; // size of table
JavaScript does not have block scope, so deIining variables in blocks can conIuse programmers who are
experienced with other C Iamily languages. DeIine all variables at the top oI the Iunction.
Use oI global variables should be minimized. Implied global variables should never be used.
Fncion Declaaion
All Iunctions should be declared beIore they are used. Inner Iunctions should Iollow the var statement.
This helps make it clear what variables are included in its scope.
There should be no space between the name oI a Iunction and the ( (leIt parenthesis) oI its parameter list.
There should be one space between the ) (right parenthesis) and the { (leIt curly brace) that begins the
statement body. The body itselI is indented Iour spaces. The (right curly brace) is aligned with the line
containing the beginning oI the declaration oI the Iunction.
function outer(c, d) {
var e = c * d;
function inner(a, b) {
return (e * a) + b;

return inner(0, 1);

10/17/11 Code Conenion fo he JaaScip Pogamming Langage
3/8 jaacip.cockfod.com/code.hml
Thi conenion ok ell ih JaaScip becae in JaaScip, fncion and objec lieal can be
placed anhee ha an epeion i alloed. I poide he be eadabili ih inline fncion and
comple ce.
function getElementsByClassName(className) {
var results = [];
walkTheDOM(document.body, function (node) {
var a; // array of class names
var c = node.className; // the node's classname
var i; // loop counter
// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.
if (c) {
a = c.split(' ');
for (i = 0; i < a.length; i += 1) {
if (a[i] === className) {
results.push(node);
break;



);
return results;

If a fncion lieal i anonmo, hee hold be one pace beeen he od function and he ( (lef
paenhei). If he pace i omied, hen i can appea ha he fncion' name i function, hich i an
incoec eading.
div.onclick = function (e) {
return false;
;
that = {
method: function () {
return this.datum;
,
datum: 0
;
Ue of global fncion hold be minimied.
When a fncion i o be inoked immediael, he enie inocaion epeion hold be apped in
paen o ha i i clea ha he ale being podced i he el of he fncion and no he fncion
ielf.
var collection = (function () {
var keys = [], values = [];
return {
get: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
return values[at];

,
10/17/11 Code Conenion fo he JaaScip Pogamming Langage
4/8 jaacip.cockfod.com/code.hml
set: function (key, value) {
var at = keys.indexOf(key);
if (at < 0) {
at = keys.length;

keys[at] = key;
values[at] = value;
,
remove: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
keys.splice(at, 1);
values.splice(at, 1);


;
());
Name
Names should be Iormed Irom the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9),
and _ (underbar). Avoid use oI international characters because they may not read well or be understood
everywhere. Do not use $ (dollar sign) or \ (backslash) in names.
Do not use _ (underbar) as the Iirst character oI a name. It is sometimes used to indicate privacy, but it
does not actually provide privacy. II privacy is important, use the Iorms that provide private members.
Avoid conventions that demonstrate a lack oI competence.
Most variables and Iunctions should start with a lower case letter.
Constructor Iunctions which must be used with the new preIix should start with a capital letter. JavaScript
issues neither a compile-time warning nor a run-time warning iI a required new is omitted. Bad things can
happen iI new is not used, so the capitalization convention is the only deIense we have.
Global variables should be in all caps. (JavaScript does not have macros or constants, so there isn't much
point in using all caps to signiIy Ieatures that JavaScript doesn't have.)
Saemen
Simple Saemen
Each line should contain at most one statement. Put a ; (semicolon) at the end oI every simple statement.
Note that an assignment statement which is assigning a Iunction literal or object literal is still an assignment
statement and must end with a semicolon.
JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in
the presence oI semicolon insertion. The only expressions that should be used as statements are
assignments and invocations.
Compond Saemen
Compound statements are statements that contain lists oI statements enclosed in { (curly braces).
10/17/11 Code Conenion fo he JaaScip Pogamming Langage
5/8 jaacip.cockfod.com/code.hml
The encloed aemen hold be indened fo moe pace.
The { (lef cl bace) hold be a he end of he line ha begin he compond aemen.
The (igh cl bace) hold begin a line and be indened o align ih he beginning of he line
conaining he maching { (lef cl bace).
Bace hold be ed aond all aemen, een ingle aemen, hen he ae pa of a
conol ce, ch a an if o for aemen. Thi make i eaie o add aemen iho
accidenall inodcing bg.
Label
Saemen label ae opional. Onl hee aemen hold be labeled: while, do, for, switch.
rern Saemen
A return aemen ih a ale hold no e ( ) (paenhee) aond he ale. The en ale
epeion m a on he ame line a he return keod in ode o aoid emicolon ineion.
if Saemen
The if cla of aemen hold hae he folloing fom:
if (condition) {
statements


if (condition) {
statements
else {
statements


if (condition) {
statements
else if (condition) {
statements
else {
statements

for Saemen
A for cla of aemen hold hae he folloing fom:
for (initialiation; condition; update) {
statements

for (variable in object) {
if (filter) {
statements


10/17/11 Code Conenion fo he JaaScip Pogamming Langage
6/8 jaacip.cockfod.com/code.hml
The fi fom hold be ed ih aa and ih loop of a pedeeminable nmbe of ieaion.
The econd fom hold be ed ih objec. Be aae ha membe ha ae added o he poope
of he object ill be inclded in he enmeaion. I i ie o pogam defeniel b ing he
hasOwnProperty mehod o diingih he e membe of he object:
for (variable in object) {
if (object.hasOwnProperty(variable)) {
statements


while Saemen
A while aemen hold hae he folloing fom:
while (condition) {
statements

do Saemen
A do aemen hold hae he folloing fom:
do {
statements
while (condition);
Unlike he ohe compond aemen, he do aemen ala end ih a ; (emicolon).
switch Saemen
A switch aemen hold hae he folloing fom:
switch (epression) {
case epression:
statements
default:
statements

Each case i aligned ih he switch. Thi aoid oe-indenaion.
Each gop of statements (ecep he default) hold end ih break, return, o throw. Do no fall
hogh.
tr Saemen
The try cla of aemen hold hae he folloing fom:
try {
statements
10/17/11 Code Conenion fo he JaaScip Pogamming Langage
7/8 jaacip.cockfod.com/code.hml
catch (ariable) {
statements

try {
statements
catch (ariable) {
statements
finally {
statements

continue Saemen
Avoid use of the continue statement. It tends to obscure the control flow of the function.
with Saemen
The with statement should not be used.
Whiepace
Blank lines improve readability by setting off sections of code that are logically related.
Blank spaces should be used in the following circumstances:
A keyword followed by ( (left parenthesis) should be separated by a space.
while (true) {
A blank space should not be used between a function value and its ( (left parenthesis). This helps to
distinguish between keywords and function invocations.
All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated
from their operands by a space.
No space should separate a unary operator and its operand except when the operator is a word
such as typeof.
Each ; (semicolon) in the control part of a for statement should be followed with a space.
Whitespace should follow every , (comma).
Bon Sggeion
{ and []
Use { instead of new Object(). Use [] instead of new Array().
Use arrays when the member names would be sequential integers. Use objects when the member names
are arbitrary strings or names.
, (comma) Opeao
10/17/11 Code Conenion fo he JaaScip Pogamming Langage
8/8 jaacip.cockfod.com/code.hml
Avoid the use oI the comma operator except Ior very disciplined use in the control part oI for
statements. (This does not apply to the comma separator, which is used in object literals, array literals,
var statements, and parameter lists.)
Block Scope
In JavaScript blocks do not have scope. Only Iunctions have scope. Do not use blocks except as
required by the compound statements.
Assignment Epressions
Avoid doing assignments in the condition part oI if and while statements.
Is
if (a = b)
a correct statement? Or was
if (a == b)
intended? Avoid constructs that cannot easily be determined to be correct.
=== and !== Operators.
It is almost always better to use the === and !== operators. The == and != operators do type coercion.
In particular, do not use == to compare against Ialsy values.
Confusing Pluses and Minuses
Be careIul to not Iollow a + with + or ++. This pattern can be conIusing. Insert parens between them to
make your intention clear.
total = subtotal + +myInput.value;
is better written as
total = subtotal + (+myInput.value);
so that the + + is not misread as ++.
eal is Evil
The eval Iunction is the most misused Ieature oI JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or
setInterval.

You might also like