JavaScript Clean Code ðŸ›
Use meaningful and pronounceable variable names 💡
Bad :
Good :
#JSTips #CleanCode
@ProgrammingTip
Use meaningful and pronounceable variable names 💡
Bad :
const yyyymmdstr = moment().format('YYYY/MM/DD');Good :
const currentDate = moment().format('YYYY/MM/DD');#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Use default arguments instead of short circuiting or conditionals 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Use default arguments instead of short circuiting or conditionals 💡
Bad :
function createMicrobrewery(name) {
const breweryName = name || 'Hipster Brew Co.';
// ...
}Good :
function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
// ...
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Use explanatory variables 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Use explanatory variables 💡
Bad :
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
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);
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
We will read more code than we will ever write. It's important that the code we do write is readable and searchable.💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
We will read more code than we will ever write. It's important that the code we do write is readable and searchable.💡
Bad :
// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);
Good :
// Declare them as capitalized `const` globals.
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Don't add unneeded context 💡
If your class/object name tells you something, don't repeat that in your variable name.
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Don't add unneeded context 💡
If your class/object name tells you something, don't repeat that in your variable name.
Bad :
const Car = {
carMake: 'Honda',
carModel: 'Accord',
carColor: 'Blue'
};
function paintCar(car) {
car.carColor = 'Red';
}Good :
const Car = {
make: 'Honda',
model: 'Accord',
color: 'Blue'
};
function paintCar(car) {
car.color = 'Red';
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Functions should do one thing 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Functions should do one thing 💡
Bad :
function emailClients(clients) {
clients.forEach((client) => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}Good :
function emailActiveClients(clients) {
clients
.filter(isActiveClient)
.forEach(email);
}
function isActiveClient(client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Don't use flags as function parameters 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Don't use flags as function parameters 💡
Bad :
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}Good :
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Avoid negative conditionals 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Avoid negative conditionals 💡
Bad :
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}Good :
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Use getters and setters 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Use getters and setters 💡
Bad :
function makeBankAccount() {
return {
balance: 0,
// ...
};
}
const account = makeBankAccount();
account.balance = 100;Good :
function makeBankAccount() {
let balance = 0;
function getBalance() {
return balance;
}
function setBalance(amount) {
balance = amount;
}
return {
getBalance,
setBalance,
};
}
const account = makeBankAccount();
account.setBalance(100);âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Async/Await are even cleaner than Promises 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Async/Await are even cleaner than Promises 💡
Bad :
get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
.then((response) => {
return writeFile('article.html', response);
})
.then(() => {
console.log('File written');
})
.catch((err) => {
console.error(err);
});Good :
async function getCleanCodeArticle() {
try {
const response = await get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
await writeFile('article.html', response);
console.log('File written');
} catch(err) {
console.error(err);
}
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Only comment things that have business logic complexity. 💡
Comments are an apology, not a requirement. Good code mostly documents itself.
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Only comment things that have business logic complexity. 💡
Comments are an apology, not a requirement. Good code mostly documents itself.
Bad :
function hashIt(data) {
// The hash
let hash = 0;
// Length of string
const length = data.length;
// Loop through every character in data
for (let i = 0; i < length; i++) {
// Get character code.
const char = data.charCodeAt(i);
// Make the hash
hash = ((hash << 5) - hash) + char;
// Convert to 32-bit integer
hash &= hash;
}
}Good :
function hashIt(data) {
let hash = 0;
const length = data.length;
for (let i = 0; i < length; i++) {
const char = data.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
// Convert to 32-bit integer
hash &= hash;
}
}âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
JavaScript Clean Code ðŸ›
Use consistent capitalization 💡
Bad :
Good :
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip
Use consistent capitalization 💡
Bad :
const DAYS_IN_WEEK = 7;
const daysInMonth = 30;
const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];
function eraseDatabase() {}
function restore_database() {}
class animal {}
class Alpaca {}
Good :
const DAYS_IN_WEEK = 7;
const DAYS_IN_MONTH = 30;
const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles'];
function eraseDatabase() {}
function restoreDatabase() {}
class Animal {}
class Alpaca {}
âž–âž–âž–âž–âž–âž–
#JSTips #CleanCode
@ProgrammingTip