es6 programming style

Block-level scopes

(1) let replaces var

ES6 proposes two new commands for declaring variables: let and const. Among them, let can completely replace var, because they have the same semantics, and let has no side effects.

'use strict';

if (true) {
  let x = 'hello';
}

for (let i = 0; i < 10; i++) {
  console.log(i);
}

If the above code replaces let with var, it actually declares two global variables, which is obviously not intended. Variables should only be valid within the block of code they declare, which the VaR command cannot do.

The var command has variable boost utility, but the let command does not have this problem.

'use strict';

if(true) {
  console.log(x); // ReferenceError
  let x = 'hello';
}

If the above code uses var instead of let, the line console.log will not report an error, but will output undefined because the variable declaration is promoted to the head of the code block. This violates the principle of declaring variables before using them.

So, instead of using the var command, let command is recommended.

Global Constants and Thread Safety

Between let and const, const is recommended as a priority, especially in the global environment. Variables should not be set, but constants should only be set.

Const is better than let for several reasons. One is that const can remind the reader that this variable should not be changed; the other is that const is more in line with the idea of functional programming, the operation does not change the value, but only new values, which is also conducive to future distributed operations; the last reason is that JavaScript compiler will optimize const, so using const more is conducive to the efficiency of the provider. That is to say, the essential difference between let and const is actually the different processing within the compiler

// bad
var a = 1, b = 2, c = 3;

// good
const a = 1;
const b = 2;
const c = 3;

// best
const [a, b, c] = [1, 2, 3];

const declarations have two other benefits. One is that the reader of the code immediately realizes that the value should not be modified, and the other is to prevent errors caused by inadvertent modification of the variable value.

All functions should be set to constants.

In the long run, JavaScript may have multi-threaded implementations (such as Intel's Rivier Trail projects), where the variables represented by let s should only appear in single-threaded code, not multi-threaded shared, which is conducive to thread safety.

Character string

Static strings always use single or reverse quotation marks, not double quotation marks. Dynamic strings use inverted quotes.

// bad
const a = "foobar";
const b = 'foo' + a + 'bar';

// acceptable
const c = `foobar`;

// good
const a = 'foobar';
const b = `foo${a}bar`;
const c = 'foobar';

Destructuring assignment

When using group members to assign variables, deconstruction assignment is preferred.

const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;

If the parameter of a function is a member of an object, the deconstruction assignment is preferred.

// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;
}

// good
function getFullName(obj) {
  const { firstName, lastName } = obj;
}

// best
function getFullName({ firstName, lastName }) {
}

If the function returns more than one value, the object's deconstruction assignment is preferred to the array's deconstruction assignment. This makes it easy to add return values later and to change the order of return values.

// bad
function processInput(input) {
  return [left, right, top, bottom];
}

// good
function processInput(input) {
  return { left, right, top, bottom };
}

const { left, right } = processInput(input);

object

Objects defined in a single line, and the last member does not end with a comma. Objects defined in multiple rows, with the last member ending with a comma

// bad
const a = { k1: v1, k2: v2, };
const b = {
  k1: v1,
  k2: v2
};

// good
const a = { k1: v1, k2: v2 };
const b = {
  k1: v1,
  k2: v2,
};

Objects are static as much as possible, and once defined, new attributes cannot be added at will. If adding attributes is unavoidable, use the Object.assign method

// bad
const a = {};
a.x = 3;

// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });

// good
const a = { x: null };
a.x = 3;

If the object's attribute name is dynamic, you can use attribute expression definition when creating the object.

// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,
};

In the code above, the last property name of the object obj needs to be calculated. At this point, it is better to use attribute expression, which is defined together with other attributes when new obj is built. In this way, all attributes are defined in one place.

In addition, the attributes and methods of objects should be expressed as concisely as possible, which is easy to describe and write.

var ref = 'some value';

// bad
const atom = {
  ref: ref,

  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  ref,

  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};

array

Use the Extended Operator (...) Copy arrays.

// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];
//Using the Array. front method, objects similar to arrays are converted to arrays.

const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);

function

The immediate execution function can be written as an arrow function.

(() => {
  console.log('Welcome to the Internet.');
})();

Where functional expressions are needed, try to replace them with arrow functions. Because it's simpler, and it binds this.

// bad
[1, 2, 3].map(function (x) {
  return x * x;
});

// good
[1, 2, 3].map((x) => {
  return x * x;
});

// best
[1, 2, 3].map(x => x * x);

The arrow function replaces Function.prototype.bind and should no longer bind this with self/_this/that

// bad
const self = this;
const boundMethod = function(...params) {
  return method.apply(self, params);
}

// acceptable
const boundMethod = method.bind(this);

// best
const boundMethod = (...params) => method.apply(this, params);

For simple, single-line, non-reusable functions, the arrow function is recommended. If the function body is complex and the number of rows is large, the traditional function writing method should be adopted.

All configuration items should be focused on one object and placed in the last parameter. Boolean values can not be used as parameters directly.

// bad
function divide(a, b, option = false ) {
}

// good
function divide(a, b, { option = false } = {}) {
}

Don't use arguments variables in the body of a function, use the rest operator (...) Instead. Because the rest operator explicitly indicates that you want to get parameters, and arguments are an array-like object, while the rest operator can provide a real array.

// bad
function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join('');
}

// good
function concatenateAll(...args) {
  return args.join('');
}

Use default value syntax to set default values for function parameters.

// bad
function handleThings(opts) {
  opts = opts || {};
}

// good
function handleThings(opts = {}) {
  // ...
}

Map structure

Note the distinction between Object and Map. Object is only used when simulating real-world entities. If you just need the data structure of key: value, use the Map structure. Because Map has built-in traversal mechanism.

let map = new Map(arr);

for (let key of map.keys()) {
  console.log(key);
}

for (let value of map.values()) {
  console.log(value);
}

for (let item of map.entries()) {
  console.log(item[0], item[1]);
}

Class

Always use Class instead of the operation that requires prototype. Because Class is more concise and easy to understand.

// 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;
  }
}

Use extends to implement inheritance because it's simpler and there's no risk of breaking instanceof operations.

// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
  Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
  return this._queue[0];
}

// good
class PeekableQueue extends Queue {
  peek() {
    return this._queue[0];
  }
}

Modular

First of all, Module grammar is the standard way to write JavaScript modules, and sticks to it. Use import instead of require.

// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;

// good
import { func1, func2 } from 'moduleA';
//Replace module.exports with export.

// Writing of commonJS
var React = require('react');

var Breadcrumbs = React.createClass({
  render() {
    return <nav />;
  }
});

module.exports = Breadcrumbs;

// The way to write ES6
import React from 'react';

class Breadcrumbs extends React.Component {
  render() {
    return <nav />;
  }
};

export default Breadcrumbs;

If the module has only one output value, it uses export default. If the module has multiple output values, it does not use export default. Expo default and ordinary export should not be used at the same time.

Do not use wildcards in module input. Because this ensures that there is a default output in your module.

// bad
import * as myObject from './importModule';

// good
import myObject from './importModule';
If the module outputs a function by default, the initials of the function name should be lowercase.

function makeStyleGuide() {
}

export default makeStyleGuide;
If the module outputs an object by default, the initials of the object name should be capitalized.

const StyleGuide = {
  es6: {
  }
};

export default StyleGuide;

Keywords: React Attribute Javascript REST

Added by JBWebWorks on Mon, 27 May 2019 20:54:42 +0300