use expressive variable / function names that describe what something is used for
NO:
for (let item of array) {
// ...
}
YES:
for (let letter of remainingLetters) {
// ...
}
don't repeat yourself - use custom functions or loops instead
NO:
let posX = Math.ceil(Math.random() * 10);
let posY = Math.ceil(Math.random() * 10);
let posZ = Math.ceil(Math.random() * 10);
YES:
function randInt(limit) {
return Math.ceil(Math.random() * limit);
}
let posX = randInt(10);
let posY = randInt(10);
let posZ = randInt(10);
NO:
let lotteryNumbers = [
randInt(45),
randInt(45),
randInt(45),
randInt(45),
randInt(45),
randInt(45),
];
YES:
let lotteryNumbers = [];
for (let i = 0; i < 6; i++) {
lotteryNumbers.push(randInt(45));
}
A function should have a single responsibility
pure functions only interact with their environment by receiving parameters and returning values
reasons for using pure functions:
- avoiding unintended data modification
- easy to reuse
non-pure function: modifies the original:
let dataArray = [10, 4, -1, 7, -1];
removeNegativeEntries(dataArray);
console.log(dataArray); // [10, 4, 7]
pure function: returns new data:
let dataArray = [10, 4, -1, 7, -1];
let cleanedDataArray = removeNegativeEntries(dataArray);
console.log(dataArray); // [10, 4, -1, 7, -1]
console.log(cleanedDataArray); // [10, 4, 7]
NO: stating the obvoius
// multiply the mass by the velocity squared and divide by two
let energy = (mass * velocity ** 2) / 2;
YES: helpful comments
// formula taken from: https://en.wikipedia.org/wiki/Kinetic_energy
let energy = (mass * velocity ** 2) / 2;
YES: "documentation comments" for users of functions
/**
* Compute the kinetic energy of a moving object (in Joules).
* Parameters: mass (in kg), velocity (in m/s)
*/
function getKineticEnergy(mass, velocity) {
return (mass * velocity ** 2) / 2;
}
extract "magic constants" to the top of the file
NO:
let lotteryNumbers = [];
for (let i = 0; i < 6; i++) {
lotteryNumbers.push(randInt(45));
}
YES:
let MAX_NUMBER = 45;
let NUMBER_OF_DRAWS = 6;
// ...
let lotteryNumbers = [];
for (let i = 0; i < NUMBER_OF_DRAWS; i++) {
lotteryNumbers.push(randInt(MAX_NUMBER));
}
files should be made up of function definitions and possibly one main function call
function main() {
foo();
bar();
// ...
}
function foo() {
// ...
}
function bar() {
// ...
}
main();
- GitHub repository: clean-code-javascript
- Book: Clean Code
- a contrarian view: Goodbye, Clean Code by Dan Abramov, React.js maintainer