請盡量避免blocking
// bad
var foo = "bar";
// better
let foo = 'bar';
// great
const foo = 'bar'
var foo = 'foo';
...
...
...
var foo = 'bar';
let foo = 'foo';
...
...
...
// failed, SyntaxError: Identifier 'foo' has already been declared
let foo = 'bar';
// pass
foo = 'bar'
const foo = '1'
const bar = 1
// bad
// Output: true
console.log(foo == bar)
// good
// Output: false
console.log(foo === bar)
// bad
function foo () {
}
// good
const foo = () => {
}
在執行任何程式碼前,JavaScript 會把函式宣告放進記憶體裡面,這樣做的優點是:可以在程式碼宣告該函式之前使用它。
// Output: foo
foo()
function foo () {
console.log('foo')
}
// bad
const foo = 'foo'
const bar = 'bar' + foo
// good
const foo = 'foo'
const bar = `bar${foo}`
// bad
const foo = {
bar: () => {}
}
// good
const foo = {
bar () {
},
}
// destruct object
const foo = { bar: 1 }
const { bar } = foo
// Output: 1
console.log(bar)
// destruct array
const foo = [1, 2, 3]
const [element1, element2, element3] = foo
// Output: 1, 2, 3
console.log(element1, element2, element3)
// destruct nested object
const foo = { foo1: { bar: 1 } }
const { foo1: { bar } } = foo
/// Output: 1
console.log(bar)
const foo = { foo: { bar: 1 } }
// TypeError: Cannot destructure property `foo2` of 'undefined' or 'null'.
const { foo1: { foo2 } } = foo
// You should...
const { foo1: { foo2 } = {} } = foo
const fs = require('fs')
fs.readFile('foo1', (errFoo1, binaryFoo1) => {
fs.readFile('foo2', (errFoo2, binaryFoo2) => {
fs.readFile('foo3', (errFoo3, binaryFoo3) => {
})
})
})
const fs = require('bluebird').promisifyAll(require('fs'))
fs.readFile('foo1')
.then(dataFoo1 => {
return fs.readFile('foo2')
})
.then(dataFoo2 => {
})
...
...
...