Good:
Use the same vocabulary for the same type of variable
Bad:
getUserInfo();
getClientData();
getCustomerRecord();
Good:
getUser();
We will read more code than we will ever write. It’s important that the code we
do write is readable and searchable. By not naming variables that end up
being meaningful for understanding our program, we hurt our readers.
Make your names searchable. Tools like
buddy.js and
can help identify unnamed constants.
Bad:
// Declare them as capitalized named constants.
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
Use explanatory variables
Bad:
const address = 'One Infinite Loop, Cupertino 95014';
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);
Good:
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
Explicit is better than implicit.
Bad:
Good:
const locations = ['Austin', 'New York', 'San Francisco'];
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
Don’t add unneeded context
Bad:
const Car = {
carMake: 'Honda',
carModel: 'Accord',
};
function paintCar(car) {
car.carColor = 'Red';
}
Good:
make: 'Honda',
model: 'Accord',
color: 'Blue'
};
function paintCar(car) {
car.color = 'Red';
}
Default arguments are often cleaner than short circuiting. Be aware that if you
use them, your function will only provide default values for undefined
arguments. Other “falsy” values such as ''
, ""
, false
, null
, 0
, andNaN
, will not be replaced by a default value.
Bad:
Good:
function createMicrobrewery(name = 'Hipster Brew Co.') {
}