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.

  1. function outer(a, b) {
  2. var c = 1,
  3. d = 2,
  4. inner;
  5. if (a > b) {
  6. inner = function () {
  7. return {
  8. r: c - d
  9. };
  10. };
  11. } else {
  12. inner = function () {
  13. return {
  14. r: c + d
  15. };
  16. };
  17. }
  18. return inner;
  19. }

Curly Braces

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

  1. // bad practice
  2. for (var i = 0; i < 10; i += 1)
  3. alert(i);
  4.  
  5. // better
  6. for (var i = 0; i < 10; i += 1) {
  7. alert(i);
  8. }
  9.  
  10. Similarly for if conditions:
  11. // bad
  12. if (true)
  13. alert(1);
  14. else
  15. alert(2);
  16.  
  17. // better
  18. if (true) {
  19. alert(1);
  20. } else {
  21. alert(2);
  22. }

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.

  1. // warning: unexpected return value
  2.  
  3. function func() {
  4. return
  5. {
  6. name: "Batman"
  7. };
  8. }

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:

  1. // warning: unexpected return value
  2. function func() {
  3. return undefined;
  4. // unreachable code follows...
  5. {
  6. name: "Batman"
  7. };
  8. }

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

  1. function func() {
  2. return {
  3. name: "Batman"
  4. };
  5. }

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:

  1. // generous and consistent spacing makes the code easier to read allowing it to "breathe"
  2. var d = 0,
  3. a = b + 1;
  4. if (a && b && c) {
  5. d = a % c;
  6. a += d;
  7. }
  8.  
  9. // antipattern
  10. // missing or inconsistent spaces make the code confusing
  11. var d= 0,
  12. a =b+1;
  13. if (a&& b&&c) {
  14. d=a %c;
  15. a+= d;
  16. }

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

JavaScript Patterns 2.9 Coding Conventions的更多相关文章

  1. JavaScript Patterns 2.10 Naming Conventions

    1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the word ...

  2. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  3. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  4. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  5. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  6. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  7. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  8. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  9. JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns

    In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...

随机推荐

  1. An Introduction to Garbage Collection(垃圾回收简介)

    1. Introduction 2. Principles 3. Advantages 4. Disadvantages 5. 常见的垃圾回收技术 5.1. 跟踪式垃圾回收 5.1.1. 基本算法 5 ...

  2. CentOS6.5菜鸟之旅:文件权限详解

    一.前言 Linux下所有资源.设备均被视作文件来操作,而文件权限则是决定用户可各文件操作的范围,无论是平时使用Linux,还是写程序均涉及这方面.以下为个人学习的整理,供以后查阅. 二. 三种权限 ...

  3. CentOS6.5菜鸟之旅:安装VirtualBox4.3

    一.下载VirtualBox的RHEL软件库配置文件 cd /etc/yum.repos.d wget http://download.virtualbox.org/virtualbox/rpm/rh ...

  4. UnityShader快速上手指南(三)

    简介 这一篇还是一些基本的shader操作:裁剪.透明和法向量的应用 (纠结了很久写不写这些,因为代码很简单,主要是些概念上的东西) 先来看下大概的效果图:(从左到右依次是裁剪,透明,加了法向量的透明 ...

  5. 怎样计算一个整数的位数&并把每一位上的数字保存下来

    用循环来解决~~ M每次除以10, 再用一个变量count来计数,每循环一次 加1,直到这个数除去10后的数小于10 ,count再加1就可以了 实例:整数M=4325, 第一次:4325/10=43 ...

  6. 自定义tab在地图进行分页显示

    @{ ViewBag.Title = "GIS地图"; Layout = null; } @model HFSoft.Plat.UIWeb.Models.MapShowDataVO ...

  7. 重新想象 Windows 8 Store Apps (69) - 其它: 自定义启动屏幕, 程序的运行位置, 保持屏幕的点亮状态, MessageDialog, PopupMenu

    [源码下载] 重新想象 Windows 8 Store Apps (69) - 其它: 自定义启动屏幕, 程序的运行位置, 保持屏幕的点亮状态, MessageDialog, PopupMenu 作者 ...

  8. javascript类的理解和使用

    距离上次写博客已经过去好几个月了,现在手里的项目正好都结束了,闲暇之后开始理一下开发中一些问题,这次说一下javascript当中的类,可能很多人对于写惯了前台页面效果的coder来说,对于javas ...

  9. csharp:Compare two DataTables to rows in one but not the other

    /// <summary> /// 账面数据 Accounting /// </summary> /// <returns></returns> Dat ...

  10. java之StringBuilder类详解

    StringBuilder 非线程安全的可变字符序列 .该类被设计用作StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍).如果可能,建议优先采用该类,因为在 ...