const plus1 = a => a + 1; const mult2 = a => a * 2; // bad mult2(plus1(5)); // => 12 // good const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val); const addThenMult = pipeline(plus1, mult2); addThenMult(5); // => 12
缓存缓存性能测试,大数据结构和任何高代价的操作。
// bad const contains = (arr, value) => Array.prototype.includes ? arr.includes(value) : arr.some(el => el === value); contains(["foo", "bar"], "baz"); // => false // good const contains = (() => Array.prototype.includes ? (arr, value) => arr.includes(value) : (arr, value) => arr.some(el => el === value) )(); contains(["foo", "bar"], "baz"); // => false
变量const 优于 let, let 优于 var。
// bad var obj = {}; obj["foo" + "bar"] = "baz"; // good const obj = { ["foo" + "bar"]: "baz" };
条件判断用多个if,优于 if 、else if、else 和switch。
// bad var grade; if (result < 50) grade = "bad"; else if (result < 90) grade = "good"; else grade = "excellent"; // good const grade = (() => { if (result < 50) return "bad"; if (result < 90) return "good"; return "excellent"; })();
对象的操作避免使用for...in。
const shared = { foo: "foo" }; const obj = Object.create(shared, { bar: { value: "bar", enumerable: true } }); // bad for (var prop in obj) { if (obj.hasOwnProperty(prop)) console.log(prop); } // good Object.keys(obj).forEach(prop => console.log(prop));
使用map合理使用的情况下,map更强大:
// bad const me = { name: "Ben", age: 30 }; var meSize = Object.keys(me).length; meSize; // => 2 me.country = "Belgium"; meSize++; meSize; // => 3 // good const me = Map(); me.set("name", "Ben"); me.set("age", 30); me.size; // => 2 me.set("country", "Belgium"); me.size; // => 3
Curry在别的语言里有Curry的一席之地,但在JS里避免使用。不然会是代码阅读困难。
// bad const sum = a => b => a + b; sum(5)(3); // => 8 // good const sum = (a, b) => a + b; sum(5, 3); // => 8
可读性不要使用自以为是的技巧:
// bad foo || doSomething(); // good if (!foo) doSomething(); // bad void function() { /* IIFE */ }(); // good (function() { /* IIFE */ }()); // bad const n = ~~3.14; // good const n = Math.floor(3.14);
代码重用对写些小型、组件化、可重用的方法。
// bad arr[arr.length - 1]; // good const first = arr => arr[0]; const last = arr => first(arr.slice(-1)); last(arr); // bad const product = (a, b) => a * b; const triple = n => n * 3; // good const product = (a, b) => a * b; const triple = product.bind(null, 3);
依赖减少第三方库的使用。当你无法完成某项工作时可以使用,但不要为了一些能自己实现的小功能就加载一个很大的库。
// bad var _ = require("underscore"); _.compact(["foo", 0])); _.unique(["foo", "foo"]); _.union(["foo"], ["bar"], ["foo"]); // good const compact = arr => arr.filter(el => el); const unique = arr => [...Set(arr)]; const union = (...arr) => unique([].concat(...arr)); compact(["foo", 0]); unique(["foo", "foo"]); union(["foo"], ["bar"], ["foo"]);
英文原文 Frontend Guidelines