A mostly reasonable approach to JavaScript
Note: this guide is base on airbnb guide Airbnb JavaScript Style Guide, it reinforces the most important rules and overwrites some of them.
- 1.1 Method Naming: Methods should be named with a verb in infinitive.
// bad
function validating() {
//...
};
// good
function validate() {
// ...
};
- 2.1 Use braces with all single-line blocks.
// bad
if (test) return false;
// good
if (test) {
return false;
}
- 3.1 Use soft tabs (space character) set to 4 spaces.
// bad
function foo() {
∙let name;
}
// bad
function bar() {
∙∙let name;
}
// good
function baz() {
∙∙∙∙let name;
}
- 4.1 Async/Await: use
async/await
instead ofthen
(promises)
// bad
const fetchUser = url => getAuthHeader().then(
authorization => fetch(url, { headers: {authorization} })
).then(
response => response.json
).then(
data => new User(data.user)
)catch(
err => console.log(err);
);
// good
const fetchUser = async url => {
try {
const response = await fetch(url, {
credentials: 'same-origin',
headers: {
authorization: await getAuthHeader()
}
});
const data = await response.json();
return new User(data.user);
} catch (err) {
console.log(err);
throw err;
}
}