Declare the variable’s new posture
Let instead of var
Before ES6 we used var to declare a variable, but it had a lot of drawbacks:
- Since there is no block-level scope, it is easy to declare global variables
- Variable ascension
- You can repeat that remember that interview question?
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function() { console.log(i); }; } a[6](); // 10 a[7](); // 10 a[8](); // 10 a[9](); / / 10Copy the code
So, why don’t you use let now?
Sometimes const is better than let
The only difference between const and LET is that const cannot be changed, so when declaring variables, especially global variables that can be easily changed, use const whenever possible.
- Better code semantics, constants at first sight.
- Another reason is that JavaScript compilers are better optimized for const than let. Using const more often improves the efficiency of your program.
- All functions should be set to constants.
Dynamic string
Do not use “double quotation marks”, always use single or back quotation marks
// low
const a = "foobar";
const b = 'foo' + a + 'bar';
// best
const a = 'foobar';
const b = `foo${a}bar`;
const c = 'foobar';
Copy the code
Deconstruct the operation of assignment
Variable assignment
When assigning to a variable using an array member, use destruct assignment whenever possible.
const arr = [1, 2, 3, 4];
// low
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
Copy the code
Function pass object
Function arguments that are members of an object use destruct assignment preferentially.
// low
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// good
function getFullName({ firstName, lastName }) {
}
Copy the code
If a function returns more than one value, use the deconstructed assignment of an object over the deconstructed assignment of an array. This makes it easy to add the return values later and change the order in which they are returned.
// low
function processInput(input) {
return [left, right, top, bottom];
}
// good
function processInput(input) {
return { left, right, top, bottom };
}
const { left, right } = processInput(input);
Copy the code
Details about the object
The comma
Single-line defined objects do not end with a comma:
// low
const a = { k1: v1, k2: v2, };
// good
const a = { k1: v1, k2: v2 };
Copy the code
Objects defined on multiple lines should retain commas:
// low
const b = {
k1: v1,
k2: v2
};
// good
const b = {
k1: v1,
k2: v2,
};
Copy the code
The one-time initialization is complete
Do not add new attributes to an object after declaring it:
// low
const a = {};
a.x = 3;
// good
const a = { x: null };
a.x = 3;
Copy the code
If you must, use Object.assign:
const a = {};
Object.assign(a, { x: 3 });
Copy the code
If the property name of the object is dynamic, we can use the property expression definition when creating the object:
// low
const obj = {
id: 5,
name: 'San Francisco'}; obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true};Copy the code
A little bit more succinct
When defining objects, be as concise as possible:
var ref = 'some value';
// low
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
returnatom.value + value; }}; // good const atom = { ref, value: 1, addValue(value) {returnatom.value + value; }};Copy the code
An array of
.
Using extension operators (…) Copy array:
/ / is still in useforConst len = items.length; const itemsCopy = [];let i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// cool !
const itemsCopy = [...items];
Copy the code
Don’t talk to me about class arrays
Convert an array-like object into an Array using the array. from method:
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
Copy the code
function
Arrow function =>
The execute now function can be written as an arrow function:
(() => {
console.log('Welcome to the Internet.'); }) ();Copy the code
Write arrow functions to make your code look simple and elegant:
// low
[1, 2, 3].map(function (x) {
return x * x;
});
// cool !
[1, 2, 3].map(x => x * x);
Copy the code
Do not pass booleans directly into functions
// low
function divide(a, b, option = false ) {
}
// good
function divide(a, b, { option = false} = {}) {}Copy the code
Stop using arguments!
Use rest operators (…) Instead, the REST operator can provide a real array.
// low
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join(' ');
}
// good
functionconcatenateAll(... args) {return args.join(' ');
}
Copy the code
Try setting the default value when passing parameters?
// low
function handleThings(opts) {
opts = opts || {};
}
// good
function handleThings(opts = {}) {
// ...
}
Copy the code
The Object? The Map!
Simple key-value pair priority Map
For simple key: value structures, Map is recommended because it provides a convenient traversal mechanism.
letmap = new Map(arr); // Iterate over the key valuefor (letkey of map.keys()) { console.log(key); } // Iterate over valuefor (letvalue of map.values()) { console.log(value); } // Iterate over the key and value valuesfor (let item of map.entries()) {
console.log(item[0], item[1]);
}
Copy the code
More concise and intuitive class syntax
// low
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);
returnvalue; }}Copy the code
modular
The introduction of the module
Use import instead of require, because Module is the standard way to write Javascript modules.
// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;
// good
import { func1, func2 } from 'moduleA';
Copy the code
Output module
Exports: module. Exports:
import React from 'react';
class Breadcrumbs extends React.Component {
render() {
return<nav />; }};export default Breadcrumbs;
Copy the code
- To output a single value, use
export default
- Output multiple values using
export
export default
With the ordinaryexport
Don’t use both
Coding standards
- The module outputs a function that should start with a lowercase letter:
function getData() {}export default getData;
Copy the code
- The module outputs an object that should begin with a capital letter
const Person = {
someCode: {
}
};
export default Person ;
Copy the code