JavaScript Patterns 2.9 Coding Conventions

It’s important to establish and follow coding conventions—they make your code
consistent, predictable, and much easier to read and understand. A new developer
joining the team can read through the conventions and be productive much sooner,
understanding the code written by any other team member.

Indentation

The rule is simple—anything within curly braces. This means the bodies of
functions, loops (do, while, for, for-in), ifs, switches, and object properties
in the object literal notation.


function outer(a, b) {
var c = 1,
d = 2,
inner;
if (a > b) {
inner = function () {
return {
r: c - d
};
};
} else {
inner = function () {
return {
r: c + d
};
};
}
return inner;
}

Curly Braces

Curly braces should always be used, even in cases when they are optional.


// bad practice
for (var i = 0; i < 10; i += 1)
alert(i);

// better
for (var i = 0; i < 10; i += 1) {
alert(i);
}

Similarly for if conditions:
// bad
if (true)
alert(1);
else
alert(2);

// better
if (true) {
alert(1);
} else {
alert(2);
}

Opening Brace Location

semicolon insertion mechanism—JavaScript is not picky when you choose not to
end your lines properly with a semicolon and adds it for you.


// warning: unexpected return value

function func() {
return
{
name: "Batman"
};
}

If you expect this function to return an object with a  name property,
you’ll be surprised. Because of the implied semicolons, the function returns
undefined. The preceding code is equivalent to this one:


// warning: unexpected return value
function func() {
return undefined;
// unreachable code follows...
{
name: "Batman"
};
}

In conclusion, always use curly braces and always put the opening one on the
same line as the previous statement:

function func() {
return {
name: "Batman"
};
}

White Space

Good places to use a white space include:

? After the semicolons that separate the parts of a for loop: for example,
for (var i= 0; i < 10; i += 1) {...}

? Initializing multiple variables (i and max) in a for loop:  for (var i
= 0, max = 10; i < max; i += 1) {...}

? After the commas that delimit array items: var a = [1, 2, 3];

? After commas in object properties and after colons that divide property
names and their values: var o = {a: 1, b: 2};

? Delimiting function arguments: myFunc(a, b, c)

? Before the curly braces in function declarations: function myFunc() {}

? After function in anonymous function expressions:  var myFunc =
function () {};

Another good use for white space is to separate all operators and their
operands with

spaces, which basically means use a space before and after  +, 
-,  *,  =,  <,  >,  <=,  >=,  = =
=,  != =, &&, ||, +=, and so on:


// generous and consistent spacing makes the code easier to read allowing it to "breathe"
var d = 0,
a = b + 1;
if (a && b && c) {
d = a % c;
a += d;
}

// antipattern
// missing or inconsistent spaces make the code confusing
var d= 0,
a =b+1;
if (a&& b&&c) {
d=a %c;
a+= d;
}

And a final note about white space—curly braces spacing. It’s good to use a
space:

? Before opening curly braces ({) in functions,  if-else cases, loops,
and object literals

? Between the closing curly brace (}) and else or while

时间: 2024-10-05 22:32:06

JavaScript Patterns 2.9 Coding Conventions的相关文章

JavaScript Patterns 2.10 Naming Conventions

1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the words in lowercase, only capitalizing the first letter in each word. upper camel case, as in  MyConstructor(), lower  camel  case,  as  in  myFunction(),

JavaScript Patterns 6.3 Klass

Commonalities • There’s a convention on how to name a method, which is to be considered the constructor of the class. • Classes inherit from other classes. • There’s access to the parent class (superclass) from within the child class. The function ta

Qt官方教程翻译——QML Coding Conventions

附网址:http://qt-project.org/doc/qt-5/qml-codingconventions.html QML Coding Conventions 这个文档包含了QML的编码规范,我们将这个规范应用在全部文档和例程当中并推荐大家遵守. QML Object Declarations 在我们的文档和例子中,QML object attributes总是像下面这样的结构: id property declarations signal declarations JavaScri

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"  One reason

JavaScript Patterns 2 Essentials - Writing Maintainable Code

Revisiting the code after some time has passed requires: ? Time to relearn and understand the problem ? Time to understand the code that is supposed to solve the problem As the application matures, many other things happen that require your code to b

JavaScript Patterns 7.1 Singleton

7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =

JavaScript Patterns 2.12 Writing API Docs

Free and open source tools for doc generation: the JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/) and YUIDoc (http://yuilibrary.com/projects/yuidoc). Process of generating API documentation ? Writing specially formatted code blocks ? Running

JavaScript Patterns 2.11 Writing Comments

Document all functions, their arguments and return values, and also any interesting or unusual algorithm or technique. Think of the comments as hints to the future readers of the code; the readers need to understand what your code does without readin