Intro
Today's Agenda
Our today's agenda is how to write clean code with javascript.
Avoid Magic Numbers
Don't use random numbers in your code because your teammates may not be able to figure out what they are.
You should name them as descriptive constants.
Example
// bad
if (num >= 8 && num <= 20) {
// ...
}
// Good
const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 20;
if (num >= MIN_PASSWORD_LENGTH && num <= MAX_PASSWORD_LENGTH) {
// ...
}
Avoid taking Boolean Flags in Function
When your function requires a boolean parameter to do something it means your function is doing more than one thing which not a good practice.
You can split your function into different functions. This way your code is easy to test and debug.
Example
const TAX = 0.05;
const PRO_TAX = 0.01;
// bad
function getPrice(item, isPro) {
if (isPro) {
return item.price + item.price * PRO_TAX;
} else {
return item.price + item.price * TAX;
}
}
// good
function getPrice(item) {
return item.price + item.price * TAX;
}
function getProPrice(item) {
return item.price + item.price * PRO_TAX;
}
Avoid Extra Context
When you create an object
, then you should avoid adding additional context to it.
Example
// bad
const user = {
userName: 'foo',
userID: 'bar',
isUserPro: false
}
// good
const user = {
name: 'baz',
ID: '443',
isPro: true
}
Declaring Variables
You can declare variables on the same line by separating them with a ,
.
Example
// bad
let a = 'baz';
let b = 'foo';
// good
let a = 'baz', b = 'foo';
Using Async/Await
Promises are a very clean way of dealing with asynchronous code (if compared to callbacks).
But in modern JavaScript, we have an even cleaner way to handle asynchronous code i.e, Async/Await.
Async/Await is just syntactic sugar over the promise API.
const API_URL = 'https://jsonplaceholder.typicode.com/todos/1';
// bad
fetch(API_URL)
.then(res => res.json())
.then(json => show(json))
// good
async function showTodo() {
const data = await (await fetch(API_URL)).json()
show(data)
}
Conclusion
Here is a Github repo having tons of tips for writing clean with javascript.
ryanmcdermott / clean-code-javascript
๐ Clean Code concepts adapted for JavaScript
JavaScript does not enforces us to write good code. Due to this we often write that just works nobody knows how, but it just works.
But with tools like eslint and typescript, we prevent it to some extent. Here is a post to help write good code with eslint.
Article No Longer Available
Share your favorite tips for writing clean code below.
Top comments (0)