5 ways to make your JavaScript codebase cleaner

5 ways to make your JavaScript codebase cleaner

1. Use default parameters instead of short-circuiting or conditionals

Default arguments are usually cleaner than short-circuiting.

function SomeMethod(paramThatCanBeUndefined) {

   const localValue = paramThatCanBeUndefined || "Default Value";
   console.log(localValue)
   // ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue

Try the following:

function SomeMethod(
  console.log(paramThatCanBeUndefined)
  // ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue

Statement: Falsy values ​​such as '', "", false, null, 0, and NaN will not be replaced by default values:

function SomeMethod(paramThatCanBeUndefined = "Default Value") {        
  console.log(paramThatCanBeUndefined)  
  // ...
}
SomeMethod(null) // will not Default Value, will null Instead
SomeMethod("SomeValue") // SomeValue

2. Handling multiple conditions

const conditions = ["Condition 2","Condition String2"];
someFunction(str){
  if(str.includes("someValue1") || str.includes("someValue2")){
    return true
  }else{
    return false
  }
}

A cleaner way to do this is:

someFunction(str){
   const conditions = ["someValue1","someValue2"];
   return conditions.some(condition=>str.includes(condition));
}

3. Replace switches with dynamic key-value pairs (i.e. object literals)

Switch version (or replace the switch with an if/else):

const UserRole = {
  ADMIN: "Admin",
  GENERAL_USER: "GeneralUser",
  SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){


  switch(userRole){
    case UserRole.ADMIN:
      return "/admin"
    case UserRole.GENERAL_USER:
        return "/GENERAL_USER"
    case UserRole.SUPER_ADMIN:
        return "/superadmin"
    default:
      return "/" 
  }

}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path

// More cases if new arrive
// You can think if else instead of switch

Dynamic key-value pair version:

const UserRole = {
   ADMIN: "Admin",
   GENERAL_USER: "GeneralUser",
   SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){
 const appRoute = {
  [UserRole.ADMIN]: "/admin",
  [UserRole.GENERAL_USER]: "/user",
  [UserRole.SUPER_ADMIN]: "/superadmin"
 };
 return appRoute[userRole] || "Default path";
}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path
// No more switch/if-else here.
// Easy to Further expansion

4. Avoid too many function parameters

function myFunction(employeeName,jobTitle,yrExp,majorExp){
 return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 years of experience in Project Management
// You can call it via
console.log(myFunction("John","Project Manager",12,"Project Management"))
// ***** PROBLEMS ARE *****
// Violation of 'clean code' principle
// Parameter sequencing is important
// Unused Params warning if not used
// Testing need to consider a lot of edge cases.

Here's a cleaner way to do it:

function myFunction({employeeName,jobTitle,yrExp,majorExp}){
 return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 years of experience in Project Management
// You can call it via
const mockTechPeople = {
  employeeName:"John",
  jobTitle:"Project Manager",
  yrExp:12,
  majorExp:"Project Management"
}
console.log(myFunction(mockTechPeople))
// ES2015/ES6 destructuring syntax is in action
// map your desired value to variable you need.

5. Use Object.assign to set the default object

This seems cumbersome:

const someObject = {
 title: null,
 subTitle: "Subtitle",
 buttonColor: null,
 disabled: true
};
function createOption(someObject) {
 someObject.title = someObject.title || "Default Title";
 someObject.subTitle = someObject.subTitle || "Default Subtitle";
 someObject.buttonColor = someObject.buttonColor || "blue";
 someObject.disabled = someObject.disabled !== undefined ? someObject.disabled : true;
 return someObject
}
console.log(createOption(someObject));

// Output be like 
// {title: 'Default Title', subTitle: 'Subtitle', buttonColor: 'blue', disabled: true}

This approach looks better:

const someObject = {
  title: null,
  subTitle: "Subtitle",
  buttonColor: null,
  disabled: true
 };
 function createOption(someObject) {
  const newObject = Object.assign({
   title: "Default Title",
   subTitle: "Default Subtitle",
   buttonColor: "blue",
   disabled: true
 },someObject)
 return newObject
 }
 console.log(creteOption(someObject));

This concludes this article about 5 ways to make your JavaScript codebase cleaner. For more information about 5 ways to make your JavaScript codebase cleaner, please search for previous articles on 123WORDPRESS.COM or continue browsing the related articles below. I hope you will support 123WORDPRESS.COM in the future! Thank you for reading

You may also be interested in:
  • JavaScript code library cookieLibrary.js that writes cookies
  • Building a JS code base from the ground up
  • Simple usage of java FastJson
  • Detailed explanation of several solutions for JavaScript interruption requests
  • Vue.js performance optimization N tips (worth collecting)
  • AngularJS implements the sample code of expanding and shrinking some columns of the table
  • JavaScript implements the most complete code analysis of a simple magnifying glass (ES5)
  • JavaScript to implement the most complete code analysis of simple carousel (ES6 object-oriented)
  • JavaScript to implement simple carousel chart most complete code analysis (ES5)
  • JavaScript to implement the most complete code analysis of a simple shopping cart (ES6 object-oriented)

<<:  Analysis of the process of simply deploying nginx in Docker container

>>:  Detailed explanation of how to run jmeter under Linux system and optimize local memory

Recommend

js to call the network camera and handle common errors

Recently, due to business reasons, I need to acce...

Detailed explanation of the difference between chown and chmod commands in Linux

In Linux system, both chmod and chown commands ca...

17 excellent web designs carefully crafted by startups

Startups often bring us surprises with their unco...

Detailed explanation of MySql 5.7.17 free installation configuration tutorial

1. Download the mysql-5.7.17-winx64.zip installat...

How to configure CDN scheduling using Nginx_geo module

Introducing the Geo module of Nginx The geo direc...

Why is the disk space still occupied after deleting table data in MySQL?

Table of contents 1. Mysql data structure 2. The ...

Use CSS to easily implement some frequently appearing weird buttons

background In the group, some students will ask r...

Manually install mysql5.7.10 on Ubuntu

This tutorial shares the process of manually inst...

Perfect solution for theme switching based on Css Variable (recommended)

When receiving this requirement, Baidu found many...

How to block IP and IP range in Nginx

Written in front Nginx is not just a reverse prox...

Summary of Textarea line break issues in HTML

Recently, I encountered a problem of whether the d...

Detailed explanation of MySQL slow log query

Slow log query function The main function of slow...

Docker container introduction

1. Overview 1.1 Basic concepts: Docker is an open...