Code Conventions for the JavaScript Programming Language
This is a set of coding conventions and rules for use in JavaScript programming. It is inspired by the Sun document Code Conventions for the Java Programming Language. It is heavily modified of course because JavaScript is not Java.
The long-term value of software to an organization is in direct proportion to the quality of the codebase. Over its lifetime, a program will be handled by many pairs of hands and eyes. If a program is able to clearly communicate its structure and characteristics, it is less likely that it will break when modified in the never-too-distant future.
Code conventions can help in reducing the brittleness of programs.
All of our JavaScript code is sent directly to the public. It should always be of publication quality.
Neatness counts.
JavaScript Files
JavaScript programs should be stored in and delivered as .js
files.
JavaScript code should not be embedded in HTML files unless the code is specific to a single session. Code in HTML adds significantly to pageweight with no opportunity for mitigation by caching and compression.
<script src=
filename.js>
tags should be placed as late in the body as possible. This reduces the effects of delays imposed by script loading on other page components. There is no need to use the language
or type
attributes. It is the server, not the script tag, that determines the MIME type.
Indentation
The unit of indentation is four spaces. Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tabstops. The use of spaces can produce a larger filesize, but the size is not significant over local networks, and the difference is eliminated by minification.
Line Length
Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it. Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion. The next line should be indented 8 spaces.
Comments
Be generous with comments. It is useful to leave information that will be read at a later time by people (possibly yourself) 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 of 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 meaningful. Focus on what is not immediately visible. Don't waste the reader's time with stuff like
i = 0; // Set i to zero.
Generally use line comments. Save block comments for formal documentation.
Variable Declarations
All variables should be declared before 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. Use of global variables should be minimized.
The var
statement should be the first statement in the function body.
It is preferred that each variable be given its own line and comment. They should be listed in alphabetical order if possible.
var currentEntry, // currently selected table entry
level, // indentation level
size; // size of table
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
Function Declarations
All functions should be declared before they are used. Inner functions should follow the var
statement. This helps make it clear what variables are included in its scope.
There should be no space between the name of a function and the (
(left parenthesis) of its parameter list. There should be one space between the )
(right parenthesis) and the {
(left curly brace) that begins the statement body. The body itself is indented four spaces. The }
(right curly brace) is aligned with the line containing the beginning of the declaration of the function.
function outer(c, d) {
var e = c * d; function inner(a, b) {
return (e * a) + b;
} return inner(0, 1);
}
This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed. It provides the best readability with inline functions and complex structures.
function getElementsByClassName(className) {
var results = [];
walkTheDOM(document.body, function (node) {
var array, // array of class names
ncn = node.className; // the node's classname // 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 list of results. if (ncn && ncn.split(' ').indexOf(className) >= 0) {
results.push(node);
}
});
return results;
}
If a function literal is anonymous, there should be one space between the word function
and the (
(left parenthesis). If the space is omitted, then it can appear that the function's name is function
, which is an incorrect reading.
div.onclick = function (e) {
return false;
}; that = {
method: function () {
return this.datum;
},
datum: 0
};
Use of global functions should be minimized.
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
var collection = (function () {
var keys = [], values = []; return {
get: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
return values[at];
}
},
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);
}
}
};
}());
Names
Names should be formed from the 26 upper and lower case letters (A
.. Z
, a
.. z
), the 10 digits (0
.. 9
), and _
(underbar). Avoid use of 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 first or last character of a name. It is sometimes intended to indicate privacy, but it does not actually provide privacy. If privacy is important, use the forms that provide private members. Avoid conventions that demonstrate a lack of competence.
Most variables and functions should start with a lower case letter.
Constructor functions that must be used with the new
prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new
is omitted. Bad things can happen if new
is not used, so the capitalization convention is the only defense 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 signify features that JavaScript doesn't have.)
Statements
Simple Statements
Each line should contain at most one statement. Put a ;
(semicolon) at the end of every simple statement. Note that an assignment statement that is assigning a function 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 of semicolon insertion. The only expressions that should be used as statements are assignments and invocations.
Compound Statements
Compound statements are statements that contain lists of statements enclosed in { }
(curly braces).
- The enclosed statements should be indented four more spaces.
- The
{
(left curly brace) should be at the end of the line that begins the compound statement. - The
}
(right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching{
(left curly brace). - Braces should be used around all statements, even single statements, when they are part of a control structure, such as an
if
orfor
statement. This makes it easier to add statements without accidentally introducing bugs.
Labels
Statement labels are optional. Only these statements should be labeled: while
, do
, for
, switch
.
return
Statement
A return
statement with a value should not use ( )
(parentheses) around the value. The return value expression must start on the same line as the return
keyword in order to avoid semicolon insertion.
if
Statement
The if
class of statements should have the following form:
if (condition) {
statements
} if (condition) {
statements
} else {
statements
} if (condition) {
statements
} else if (condition) {
statements
} else {
statements
}
for
Statement
A for
class of statements should have the following form:
for (initialization; condition; update) {
statements
} for (variable in object) {
if (filter) {
statements
}
}
The first form should be used with arrays and with loops of a predeterminable number of iterations.
The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the
hasOwnProperty
method to distinguish the true members of the object:
for (variable in object) {
if (object.hasOwnProperty(variable)) {
statements
}
}
while
Statement
A while
statement should have the following form:
while (condition) {
statements
}
do
Statement
A do
statement should have the following form:
do {
statements
} while (condition);
Unlike the other compound statements, the do
statement always ends with a ;
(semicolon).
switch
Statement
A switch
statement should have the following form:
switch (expression) {
case expression:
statements
default:
statements
}
Each case
is aligned with the switch
. This avoids over-indentation. A case
label is not a statement, and should not be indented like one.
Each group of statements (except the default
) should end with break
, return
, or throw
. Do not fall through.
try
Statement
The try
class of statements should have the following form:
try {
statements
} catch (variable) {
statements
} try {
statements
} catch (variable) {
statements
} finally {
statements
}
continue
Statement
Avoid use of the continue
statement. It tends to obscure the control flow of the function.
with
Statement
The with
statement should not be used.
Whitespace
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).
Bonus Suggestions
{}
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) Operator
Avoid the use of the comma operator. (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 functions have scope. Do not use blocks except as required by the compound statements.
Assignment Expressions
Avoid doing assignments in the condition part of 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.
Use the ===
and !==
operators. The ==
and !=
operators do type coercion and should not be used.
Confusing Pluses and Minuses
Be careful to not follow a +
with +
or ++
. This pattern can be confusing. 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 ++
.
eval
is Evil
The eval
function is the most misused feature of JavaScript. Avoid it.
eval
has aliases. Do not use the Function
constructor. Do not pass strings to setTimeout
or setInterval
.
Code Conventions for the JavaScript Programming Language的更多相关文章
- Go is more about software engineering than programming language research.
https://talks.golang.org/2012/splash.article Go at Google: Language Design in the Service of Softwar ...
- What is the Best Programming Language to Learn in 2014?
It’s been a year since I revealed the best languages to learn in 2013. Once again, I’ve examined the ...
- Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax that is familiar to users of other technical
http://julialang.org/ julia | source | downloads | docs | blog | community | teaching | publications ...
- The Go Programming Language. Notes.
Contents Tutorial Hello, World Command-Line Arguments Finding Duplicate Lines A Web Server Loose End ...
- PythonStudy——高级语言 High-level programming language
高级语言 高级语言(High-level programming language)相对于机器语言(machine language,是一种指令集的体系.这种指令集,称机器码(machine code ...
- What programming language is best for a bioinformatics beginner?
probably Unix Shell scripts, Perl, or Python and R can be the best options. ---------- 1-python 2-R ...
- Java Programming Language Enhancements
引用:Java Programming Language Enhancements Java Programming Language Enhancements Enhancements in Jav ...
- Questions that are independent of programming language. These questions are typically more abstract than other categories.
Questions that are independent of programming language. These questions are typically more abstract ...
- Java语言编码规范(Java Code Conventions)
Java语言编码规范(Java Code Conventions) 名称 Java语言编码规范(Java Code Conventions) 译者 晨光(Morning) 简介 本文档讲述了Java语 ...
随机推荐
- P3942 将军令
P3942 将军令 梦里,小 F 成了一个给将军送密信的信使. 现在,有两封关乎国家生死的密信需要送到前线大将军帐下,路途凶险,时间紧迫.小 F 不因为自己的祸福而避趋之,勇敢地承担了这个任务. 不过 ...
- Java基础-集合的嵌套
Java基础-集合的嵌套 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.静态导入 静态导入是在JDK1.5后的新特性,可以减少开发的代码量,但是实际用处是很一般,静态导入的标准 ...
- IOS数组的排序和筛选
1.排序 [self.tableItems sortUsingComparator:^NSComparisonResult(GPBTeacherBrief* obj1, GPBTeacherBrief ...
- linux下常用的几个时间函数:time,gettimeofday,clock_gettime,_ftime
time()提供了秒级的精确度 1.头文件 <time.h> 2.函数原型 time_t time(time_t * timer) 函数返回从TC1970-1-1 0:0:0开始到现在的秒 ...
- memset函数使用详解
1.void *memset(void *s,int c,size_t n) 总的作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c. 2.例子#include void main(){cha ...
- 通过TodoList案例对比Vue.js的MVVM设计模式与JQuery的MVP设计模式
Vue MVVM设计模式: 在使用vue进行编程时,不会再涉及到DOM的操作,取而代之的是修改数据层,当把数据进行变更的时候,vue之中它的底层会自动的根据数据的不同帮助我们去重新渲染页面. 编码时不 ...
- poj 2728 Desert King (最优比率生成树)
Desert King http://poj.org/problem?id=2728 Time Limit: 3000MS Memory Limit: 65536K Descripti ...
- jQuery插件开发中$.extend和$.fn.extend辨析
jQuery插件开发分为两种: 1 类级别 类级别你可以理解为拓展jquery类,最明显的例子是$.ajax(...),相当于静态方法. 开发扩展其方法时使用$.extend方法,即jQuery. ...
- github 新创建repositories
1. 在github上新建repo 2. 找到改repo的地址,用命令git clone https://...., 拉取到本地 3. 打开一个单独的窗口,打开此文件夹 4. 创建自己的python ...
- 适配器在JavaScript中的体现
适配器设计模式在JavaScript中非常有用,在处理跨浏览器兼容问题.整合多个第三方SDK的调用,都可以看到它的身影. 其实在日常开发中,很多时候会不经意间写出符合某种设计模式的代码,毕竟设计模式就 ...