• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

bevacqua/js: A JavaScript Quality Guide

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

bevacqua/js

开源软件地址:

https://github.com/bevacqua/js

开源编程语言:


开源软件介绍:

function qualityGuide () {

A quality conscious and organic JavaScript quality guide

This style guide aims to provide the ground rules for an application's JavaScript code, such that it's highly readable and consistent across different developers on a team. The focus is put on quality and coherence across the different pieces of your application.

Goal

These suggestions aren't set in stone, they aim to provide a baseline you can use in order to write more consistent codebases. To maximize effectiveness, share the styleguide among your co-workers and attempt to enforce it. Don't become obsessed about code style, as it'd be fruitless and counterproductive. Try and find the sweet spot that makes everyone in the team comfortable developing for your codebase, while not feeling frustrated that their code always fails automated style checking because they added a single space where they weren't supposed to. It's a thin line, but since it's a very personal line I'll leave it to you to do the drawing.

Use together with bevacqua/css for great good!

Feel free to fork this style guide, or better yet, send Pull Requests this way!

Table of Contents

  1. Modules
  2. Strict Mode
  3. Spacing
  4. Semicolons
  5. Style Checking
  6. Linting
  7. Strings
  8. Variable Declaration
  9. Conditionals
  10. Equality
  11. Ternary Operators
  12. Functions
  13. Prototypes
  14. Object Literals
  15. Array Literals
  16. Regular Expressions
  17. console Statements
  18. Comments
  19. Variable Naming
  20. Polyfills
  21. Everyday Tricks
  22. License

Modules

This style guide assumes you're using a module system such as CommonJS, AMD, ES6 Modules, or any other kind of module system. Modules systems provide individual scoping, avoid leaks to the global object, and improve code base organization by automating dependency graph generation, instead of having to resort to manually creating multiple <script> tags.

Module systems also provide us with dependency injection patterns, which are crucial when it comes to testing individual components in isolation.

Strict Mode

Always put 'use strict'; at the top of your modules. Strict mode allows you to catch nonsensical behavior, discourages poor practices, and is faster because it allows compilers to make certain assumptions about your code.

Spacing

Spacing must be consistent across every file in the application. To this end, using something like .editorconfig configuration files is highly encouraged. Here are the defaults I suggest to get started with JavaScript indentation.

# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

Settling for either tabs or spaces is up to the particularities of a project, but I recommend using 2 spaces for indentation. The .editorconfig file can take care of that for us and everyone would be able to create the correct spacing by pressing the tab key.

Spacing doesn't just entail tabbing, but also the spaces before, after, and in between arguments of a function declaration. This kind of spacing is typically highly irrelevant to get right, and it'll be hard for most teams to even arrive at a scheme that will satisfy everyone.

function () {}
function( a, b ){}
function(a, b) {}
function (a,b) {}

Try to keep these differences to a minimum, but don't put much thought to it either.

Where possible, improve readability by keeping lines below the 80-character mark.

Semicolons;

The majority of JavaScript programmers prefer using semicolons. This choice is done to avoid potential issues with Automatic Semicolon Insertion (ASI). If you decide against using semicolons, make sure you understand the ASI rules.

Regardless of your choice, a linter should be used to catch unnecessary or unintentional semicolons.

Style Checking

Don't. Seriously, this is super painful for everyone involved, and no observable gain is attained from enforcing such harsh policies.

Linting

On the other hand, linting is sometimes necessary. Again, don't use a linter that's super opinionated about how the code should be styled, like jslint is. Instead use something more lenient, like jshint or eslint.

A few tips when using JSHint.

  • Declare a .jshintignore file and include node_modules, bower_components, and the like
  • You can use a .jshintrc file like the one below to keep your rules together
{
  "curly": true,
  "eqeqeq": true,
  "newcap": true,
  "noarg": true,
  "noempty": true,
  "nonew": true,
  "sub": true,
  "undef": true,
  "unused": true,
  "trailing": true,
  "boss": true,
  "eqnull": true,
  "strict": true,
  "immed": true,
  "expr": true,
  "latedef": "nofunc",
  "quotmark": "single",
  "indent": 2,
  "node": true
}

By no means are these rules the ones you should stick to, but it's important to find the sweet spot between not linting at all and not being super obnoxious about coding style.

Strings

Strings should always be quoted using the same quotation mark. Use ' or " consistently throughout your codebase. Ensure the team is using the same quotation mark in every portion of JavaScript that's authored.

Bad
var message = 'oh hai ' + name + "!";
Good
var message = 'oh hai ' + name + '!';

Usually you'll be a happier JavaScript developer if you hack together a parameter-replacing method like util.format in Node. That way it'll be far easier to format your strings, and the code looks a lot cleaner too.

Better
var message = util.format('oh hai %s!', name);

You could implement something similar using the piece of code below.

function format () {
  var args = [].slice.call(arguments);
  var initial = args.shift();

  function replacer (text, replacement) {
    return text.replace('%s', replacement);
  }
  return args.reduce(replacer, initial);
}

To declare multi-line strings, particularly when talking about HTML snippets, it's sometimes best to use an array as a buffer and then join its parts. The string concatenating style may be faster but it's also much harder to keep track of.

var html = [
  '<div>',
    format('<span class="monster">%s</span>', name),
  '</div>'
].join('');

With the array builder style, you can also push parts of the snippet and then join everything together at the end. This is in fact what some string templating engines like Jade prefer to do.

Variable Declaration

Always declare variables in a consistent manner, and at the top of their scope. Keeping variable declarations to one per line is encouraged. Comma-first, a single var statement, multiple var statements, it's all fine, just be consistent across the project, and ensure the team is on the same page.

Bad
var foo = 1,
    bar = 2;

var baz;
var pony;

var a
  , b;
var foo = 1;

if (foo > 1) {
  var bar = 2;
}
Good

Just because they're consistent with each other, not because of the style

var foo = 1;
var bar = 2;

var baz;
var pony;

var a;
var b;
var foo = 1;
var bar;

if (foo > 1) {
  bar = 2;
}

Variable declarations that aren't immediately assigned a value are acceptable to share the same line of code.

Acceptable
var a = 'a';
var b = 2;
var i, j;

Conditionals

Brackets are enforced. This, together with a reasonable spacing strategy will help you avoid mistakes such as Apple's SSL/TLS bug.

Bad
if (err) throw err;
Good
if (err) { throw err; }

It's even better if you avoid keeping conditionals on a single line, for the sake of text comprehension.

Better
if (err) {
  throw err;
}

Equality

Avoid using == and != operators, always favor === and !==. These operators are called the "strict equality operators," while their counterparts will attempt to cast the operands into the same value type.

Bad
function isEmptyString (text) {
  return text == '';
}

isEmptyString(0);
// <- true
Good
function isEmptyString (text) {
  return text === '';
}

isEmptyString(0);
// <- false

Ternary Operators

Ternary operators are fine for clear-cut conditionals, but unacceptable for confusing choices. As a rule, if you can't eye-parse it as fast as your brain can interpret the text that declares the ternary operator, chances are it's probably too complicated for its own good.

jQuery is a prime example of a codebase that's filled with nasty ternary operators.

Bad
function calculate (a, b) {
  return a && b ? 11 : a ? 10 : b ? 1 : 0;
}
Good
function getName (mobile) {
  return mobile ? mobile.name : 'Generic Player';
}

In cases that may prove confusing just use if and else statements instead.

Functions

When declaring a function, always use the function declaration form instead of function expressions. Because hoisting.

Bad
var sum = function (x, y) {
  return x + y;
};
Good
function sum (x, y) {
  return x + y;
}

That being said, there's nothing wrong with function expressions that are just currying another function.

Good
var plusThree = sum.bind(null, 3);

Keep in mind that function declarations will be hoisted to the top of the scope so it doesn't matter the order they are declared in. That being said, you should always keep functions at the top level in a scope, and avoid placing them inside conditional statements.

Bad
if (Math.random() > 0.5) {
  sum(1, 3);

  function sum (x, y) {
    return x + y;
  }
}
Good
if (Math.random() > 0.5) {
  sum(1, 3);
}

function sum (x, y) {
  return x + y;
}
function sum (x, y) {
  return x + y;
}

if (Math.random() > 0.5) {
  sum(1, 3);
}

If you need a "no-op" method you can use either Function.prototype, or function noop () {}. Ideally a single reference to noop is used throughout the application.

Whenever you have to manipulate an array-like object, cast it to an array.

Bad
var divs = document.querySelectorAll('div');

for (i = 0; i < divs.length; i++) {
  console.log(divs[i].innerHTML);
}
Good
var divs = document.querySelectorAll('div');

[].slice.call(divs).forEach(function (div) {
  console.log(div.innerHTML);
});

However, be aware that there is a substantial performance hit in V8 environments when using this approach on arguments. If performance is a major concern, avoid casting arguments with slice and instead use a for loop.

Bad

var args = [].slice.call(arguments);

Good

var i;
var args = new Array(arguments.length);
for (i = 0; i < args.length; i++) {
    args[i] = arguments[i];
}

Don't declare functions inside of loops.

Bad
var values = [1, 2, 3];
var i;

for (i = 0; i < values.length; i++) {
  setTimeout(function () {
    console.log(values[i]);
  }, 1000 * i);
}
var values = [1, 2 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
mikeymckay/google-spreadsheet-javascript: Read data from google spreadsheets发布时间:2022-06-24
下一篇:
denysdovhan/wtfjs: 发布时间:2022-06-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap