The JavaScript code specification for the Airbnb frontend specification

Source: Internet
Author: User
Tags shallow copy tag name hasownproperty

1 references

1.1 Use const for all references, do not use Var.

(This ensures that you cannot reassign a reference, or cause a bug or a difficulty to understand)

Bad  var a = 1;  var B = 2;//good  const A = 1;  Const B = 2;
1.2 If you must require a variable reference, use let instead of Var.

(Because let is a block-level scope, and Var is a function scope.) )

Bad  var count = 1;  if (true) {    count + = 1;  } Good, use the Let.  let count = 1;  if (true) {    count + = 1;  }
2 Objects2.1 Create an object with literal values.
BADCONST item = new Object ();//Goodconst item = {};
2.2 Shorthand for using object methods.
Badconst atom = {  value:1,  addvalue:function (value) {    return atom.value + value;  },};//goodconst at Om = {  value:1,  addvalue (value) {    return atom.value + value;  },};
2.3 Shorthand for using object property values.
Const Lukeskywalker = ' Luke Skywalker ';//bad  const OBJ = {    Lukeskywalker:lukeskywalker,  };//good  Const OBJ = {    lukeskywalker,  };
2.4 Do not call the Object.prototype method directly, such as: hasOwnProperty, propertyisenumerable, and isprototypeof
Badconsole.log (Object.hasownproperty (key));//Goodconsole.log (Object.prototype.hasOwnProperty.call (object, key );//Bestconst has = Object.prototype.hasOwnProperty; Cache the lookup once, in module scope./* or */const have = require (' has '); Console.log (Has.call (object, key));

2.5 Shallow copy objects when it is best to use ... operator rather than object.assign
Very Badconst original = {a:1, b:2};const copy = Object.assign (original, {c:3}); This mutates ' original ' delete copy.a; So does this
Badconst original = {a:1, b:2};const copy = Object.assign ({}, original, {c:3}); copy = {a:1, b:2, c:3}//goodconst original = {a:1, b:2};const copy = {... original, c:3}; copy = {a:1, b:2, C:3}const {A, ... noA} = copy; NoA = {b:2, c:3}

3 Arrays3.1 Create an array with literal values. Eslint:no-array-constructor
Badconst items = new Array ();//Goodconst items = [];
3.2 Using the expand operator ... Copies an array.
< Len ; i++) {  = items[i];  = [... items];
3.3 Using Array#from to convert a class array object to a group
const FOO = Document.queryselectorall ('. Foo '); const nodes = Array.from (foo);
4 Functions4.1 Using function declarations instead of function expressions

Why? Because function declarations are named, they are easier to identify in the call stack. In addition, the function declaration will elevate the entire function (hoisted), whereas the function expression will only elevate the reference variable name of the function. This rule allows an arrow function to replace a function expression.

Bad  const FOO = function () {  };  Good  function foo () {  }
4.2 Function Expressions:
The function expression (iife) called immediately (() = {   Console.log (' Welcome to the Internet. Please follow me. ');}) ();
4.3 never declare a function in a non-function code block (if, while, etc.) and assign that function to a variable. Browsers allow you to do this, but their parsing performance is inconsistent
Badif (currentUser) {  function test () {    console.log (' Nope. ');}  } Goodlet test;if (currentUser) {  test = () = {    Console.log (' Yup. ');}  ;}
4.4 Do not use arguments. You can choose the rest syntax ... Alternative

Why? Use... You can specify the parameters you want to pass in. In addition, the rest parameter is a true array, and arguments is an array of classes.

Bad  function Concatenateall () {    Const args = Array.prototype.slice.call (arguments);    Return Args.join (");  }  Good  function Concatenateall (... args) {    return args.join (');  }

5 arrow Function5.1 Use the arrow function notation when you must use a function expression (or pass an anonymous function).

Why? Because the arrow functions create a new This execution environment: reference Arrow Functions-javascript | MDN and ES6 arrow functions, syntax and lexical scoping, usually meet your needs, and this is more concise.

Why not? If you have a fairly complex function, you might be able to transfer the logical part to a function declaration.

Bad  [1, 2, 3].map (function (x) {    return x * x;  });  Good  [1, 2, 3].map ((x) + = {    return x * x;  });

5.2 If a function is suitable for writing on a line and has only one argument, omit the curly braces, parentheses, and return. If it's not, then don't omit it.

Why? Grammatical sugars. Readability is high in chained calls.
Why not? When you are going to return an object.

  Good  [1, 2, 3].map (x = = x * x);  Good  [1, 2, 3].reduce (total, n) = {    return total + N;  }, 0);
6 Constructors6.1 Always use class. Avoid direct operation prototype

Why? Because the class syntax is more concise and easier to read.

Bad  function Queue (contents = []) {    This._queue = [... contents];  }  Queue.prototype.pop = function () {    Const value = this._queue[0];    This._queue.splice (0, 1);    return value;  }  Good  class Queue {    Constructor (contents = []) {      This._queue = [... contents];    }    Pop () {      Const value = this._queue[0];      This._queue.splice (0, 1);      return value;    }  }

  

6.2 Using extends inheritance.

Why? Because extends is a built-in prototype inheritance method and does not break instanceof.

The 6.3 method can return this to help with chained calls.7 Modules7.1 Always use Module (import/export) 7.2 Do not use wildcards import
Bad  import * as Airbnbstyleguide from './airbnbstyleguide ',//good  import airbnbstyleguide from '. Airbnbstyleguide ';

  

7.3 Do not export directly from import
Bad  //filename es6.js  export {es6 as default} from './airbnbstyleguide ';/  /good//filename es6.js  I mport {ES6} from './airbnbstyleguide ';  Export default ES6;

  

8 iterators and generators8.1 Do not use iterators, use higher-order functions such as map () and reduce () instead of for-of

Why? This reinforces our immutable rules. Callback values that handle pure functions are easier to read, which is more important than the side effects it brings.

Const NUMBERS = [1, 2, 3, 4, 5];  Bad let  sum = 0;  for (let num of numbers) {    sum + = num;  }  sum = =;  Good let  sum = 0;  Numbers.foreach (num) = sum + = num);  sum = =;  Best (with the functional force)  Const SUM = numbers.reduce ((total, num)-= total + num, 0);  sum = = 15;

8.2 Don't use generators now?

Why? Because they are not yet well compiled into ES5. (currently stable versions of Chrome and node. JS are supported generators)

9 Variables9.1 Always use const to declare variables

If you do not do this, global variables will be generated. We need to avoid the pollution of the global namespace.

Badsuperpower = new SuperPower ();//Goodconst SuperPower = new SuperPower ();

  

9.2 declaring each variable with a const

Why? Adding new variables will make it easier, and you'll never have to worry about swapping mistakes. With.

9.3 To group all the const and let

Why? This is useful when you need to assign an assigned variable to an unassigned variable.

  Bad let  I, Len, Dragonball,      items = GetItems (),      gosportsteam = true;  Bad let  i;  Const ITEMS = GetItems ();  Let Dragonball;  Const Gosportsteam = true;  Let Len;  Good  Const Gosportsteam = true;  Const ITEMS = GetItems ();  Let Dragonball;  let I;  let length;
9.4 Assign values to variables where you need them, but put them in a reasonable position

Let and const are block-level scopes rather than function scopes.

10 Promotion10.1 var declarations are promoted to the top of the scope, but their assignments are not promoted.

Let and const are given a concept called "temporary Dead Zone (temporal Dead Zones, TDZ)". This is important for understanding why the type of is no longer secure.

10.2 The variable name of an anonymous function expression is promoted, but the function content does not. 10.3 The variable name of a named function expression is promoted, but the function name and the contents of the functional function do not. The name of the 10.4 function declaration and the body of the function will be promoted.11 comparison operators & equals11.1 precedence Use = = = and!== instead of = = and!=.11.2 conditional expressions such as if statements toboolean the expression that forces them to be evaluated by an abstract method and always adhere to the following rules:

o object is evaluated to True
o Undefined is calculated as false
o Null is calculated as false
o Boolean value is computed as a Boolean value
o number if +0,-0, or NaN is evaluated as false, otherwise true
o String if an empty string "is evaluated as false, otherwise true

12 Notes12.1 Use/ * .../as multi-line comment. Contains the types and values that describe, specify all parameters, and return values.
bad//make () returns a new element//based on the passed in tag name////@param {String} tag//@return {element} elemen Tfunction make (tag) {  //... stuff  ... return element;} good/** * Make () returns a new element * Based on the passed in tag name * * @param {String} tag * @return {element} el Ement */function make (tag) {  //... stuff  ... return element;}

  

12.2 Use//as a single line comment. A single line of comments is used on the comment object above the other line. Inserts a blank line before the comment. 12.3 Adding fixme or TODO prefixes to annotations

Help other developers quickly understand that this is a problem that needs to be reviewed, or provide a solution to the functionality that needs to be implemented. This will be different from the common annotations, as they are actionable. Use Fixme–need to figure this out or todo–need to implement.

12.4 using//FIXME: Labeling problems.
Class Calculator {  constructor () {    //FIXME:SHOULDN ' t use a global here total    = 0;  }}

  

12.5 Use//TODO: Labeling problem resolution.
Class Calculator {  constructor () {    //todo:total should is configurable by an options param    this.total = 0;
   }}
13 Blanks13.1 Use 2 spaces as indentation. 13.2 Put a space before the curly braces. 13.3 Place a space before the parentheses in the control statement (if, while, and so on).

In function calls and declarations, spaces are not added to the function's argument list.

13.4 Insert a blank line at the end of the file. 13.5 indents when using a long method chain. Use the points placed at the front. It is emphasized that this is a method call, not a new statement.

The JavaScript code specification for the Airbnb frontend specification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.