DEV Community

Sujan Maharjan
Sujan Maharjan

Posted on

JavaScript Clean Codes

Originally By Codevolution

1. Avoid magic numbers

  • Don't do this
if (password.length < 8) {
    // Display error message
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
const MIN_PASSWORD_LENGTH = 8
if (password.length < MIN_PASSWORD_LENGTH) {
    // Display error message
}
Enter fullscreen mode Exit fullscreen mode

2. Avoid additional context

  • Don't do this
const employee = {
    employeeName: 'John Doe',
    employeeAge: 26,
    employeeSalary: 40000
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
const employee = {
    name: 'John Doe',
    age: 26,
    salary: 40000
}
Enter fullscreen mode Exit fullscreen mode

3. Use default arguments instead of short-circuiting

  • Don't do this
// All products receive 10% discount
function calculateDiscount(discount){
    const minDiscount = discount || 10
    // ...Rest of the function
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
// All products receive 10% discount
function calculateDiscount(discount = 10){
    const minDiscount = discount
    // ...Rest of the function
}
Enter fullscreen mode Exit fullscreen mode

4. Restrict function arguments to 3

  • Don't do this
function toastNotification('Login Successful', duration, style, className, icon, role)
Enter fullscreen mode Exit fullscreen mode
  • Do this
const options = {
    duration: 3000,
    style: {},
    className: '',
    icon: '🙂',
    role: 'status'
}

function toastNotification('Login Successful`, options)
Enter fullscreen mode Exit fullscreen mode

5. Functions should do one thing

  • Don't do this
function notifyUsers(users) {
    users.forEach(user =>{
        const userRecord = database.lookup(user)
        if (userRecord.isSubscribed()){
            notify(user)
        }
    })
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
function notifySubscribedUsers(users) {
    users.filter(isSubscribedUser).forEach(notify)
}

function isSubscribedUser(user){
    const userRecord = database.lookup(user)
    return userRecord.isSubscribed()
}
Enter fullscreen mode Exit fullscreen mode

6. Avoid boolean flags as parameters

  • Don't do this
function getitemCost(itemCost, isMember){
    const MEMBER_DISCOUNT = 0.30
    const NORMAL_DISCOUNT = 0.10
    let cost = 0
    if(isMember){
        cost = itemCost * (1 - MEMBER_DISCOUNT)
    } else {
        cost = itemCost * (1 - NORMAL_DISCOUNT)
    }
    return cost
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
function getItemCost(itemCost) {
    const NORMAL_DISCOUNT = 0.10
    let cost = itemCost * (1- NORMAL_DISCOUNT)
    return cost
}

function getItemCostForMember(itemCost){
     const MEMBER_DISCOUNT = 0.10
    let cost = itemCost * (1- MEMBER_DISCOUNT)
    return cost
}
Enter fullscreen mode Exit fullscreen mode

7. Encapsulate Conditionals

  • Don't do this
if(status === "loading" && isEmpty(produtionList)){
    // ...Rest of the code
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
function shouldDisplayLoader (status, productList){
    return status === "loading" && isEmpty (productList);
}

if (shouldDisplayLoader(requestStatus, productList)){
    // ...Rest of the code
}
Enter fullscreen mode Exit fullscreen mode

8. Avoid contractions when naming

  • Don't do this
const curColor = "#333"
function sndNotif() {
}
function onBtnClk() {
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
const currentColor() {

}
function sendNotification(){}
function onButtonClick(){}
Enter fullscreen mode Exit fullscreen mode

9. Use prefix when naming boolean variables

  • Don't do this
const LoggedIn = true
const followers = false
Enter fullscreen mode Exit fullscreen mode
  • Do this
const isLoggedIn = true
const hasFollowers = false
Enter fullscreen mode Exit fullscreen mode

10. Use a verb when naming functions

  • Don't do this
function fullName(firstName, lastName){
    this.fullName = `${firstName} ${lastName}`
}
function fullName(){
    return `${firstName} ${lastName}
}
function count(){
    this.count = this.initialCount
}
function async products(){
    const products = await fetch('/api/products')
    return products
}
Enter fullscreen mode Exit fullscreen mode
  • Do this
function setFullName(firstName, lastName){
    this.fullName = `${firstName} ${lastName}`
}
function getFullName(){
    return `${firstName} ${lastName}
}
function resetCount(){
    this.count = this.initialCount
}
function async fetchProducts(){
    const products = await fetch('/api/products')
    return products
}
Enter fullscreen mode Exit fullscreen mode

Link to the original content: https://youtu.be/vPXzVNmCPg4

Top comments (0)