Javascript clean code tips and best practices

Simple tweaks that will make you a better developer

Complying with clean and designed code is imperative in current data and improvement advances. Moreover, since it makes your and others’ lives simpler to get, that same code in the future additionally makes a difference in creating a more professional computer program built in the industry. In this article, we have explained JavaScript clean code tips and best principles.

Destructuring Objects For Function Parameterization

Suppose we have one function which accepts some arguments and returns some new values based on calculations. Mostly we are doing the below.

JS
//This is bad 💩
const getFullName = (user) => {
  const firstName = user.firstName;
  const lastName = user.lastName;
  return `${firstName} ${lastName}`;
}

But we can do the same thing in a better way by using destructuring.

JS
//This is better ✨
const getFullName = (user) => {
  const { firstName, lastname } = user;
  return `${firstName} ${lastName}`;
}

You thought that was it, right? Nope, we can do even better. We can destructure the function parameters itself.

JS
//Way better
const getFullName = ({ firstName, lastname }) => {
  return `${firstName} ${lastName}`;
}

Keep Your Functions Short And Simple

The function should do one thing and do it well. If you have a function that is doing multiple things, then you should break it into multiple functions. This will make your code more readable and maintainable.

JS
//This is bad
const loginAndValidate = () => {
  // handles validation and login
}

//Much better
const validate = () => {}
const login = () => {}

Naming things

Guilty as charged. Every programmer has done this one way or another. I named variables and functions in a way that only I could understand (for a while at least 😁). This is a very bad practice, and it will make your code unreadable and unmaintainable. You should always name your variables and functions in a meaningful manner.

Use verbal names for their declaration, avoid abbreviations and make them a little verbose.

JS
//Not verbal, unnecessary abbreviation or abstraction 🙄
const sumCalculation = () => {}
const getS = () => {}
const add = () => {}

//Self explaining
const calculateSum = () => {}
const getSum = () => {}

When we know that method's return type is boolean, we should prefix it with is or has.

JS
const isValidEmail = validateEmail()
const hasError = validateForm()

Use plural names for arrays and collections and use proper names for variables when you are using a loop.

JS
//Wrong
const user = ['Tony', 'Bruce', 'Steve']
users.map((a) => {
  console.log(a);
})

//Correct
const users = ['Tony', 'Bruce', 'Steve']
users.map((user) => {
  console.log(users);
})

Using ternary operator

Ternary operators are very useful when you want to assign a value to a variable based on some condition. But you should avoid using nested ternary operators as it will make your code unreadable. In the example below we will replace the traditional if-else statement with a ternary operator.

JS
const age = 16;

//Traditional way 🥱
if (age < 18) {
 return "MINOR";
}
else {
 return "ADULT";
}

//Modern way with ternary operator 🤠
return age < 18 ? "MINOR" :"ADULT";

Use Arrow functions

Arrow functions was introduced in ES6. And it introduced a simple and shorter way to create functions. It has a few downsides, but you should use it whenever possible.

JS
//Normal function
function multiply(num1, num2) {
  const result = num1 * num2
  return result
}

//Arrow function 🏹
const multiply = (num1, num2) => {
  return num1 * num2
}
//or ditch the curly braces if function only contains the return statement
const multiply = (num1, num2) => num1 * num2

You can read more about the differences between arrow functions and normal functions here.

Use optional chaining

Optional chaining is a new feature introduced in ES2020. It allows you to access deeply nested object properties without worrying if the property exists or not. It will return undefined if the property doesn't exist.

JS
const data = {
  users: [
    'Tony',
    'Bruce',
    'Steve'
  ]
}

//Hard to read
if (data && data.users && data.users.length > 0) {
  console.log(data.users[0])
}

//With optional chaining ⛓️
console.log('3nd value in users: ', data?.users?.[2]) // 'Steve'
console.log('4th value in users: ', data?.users?.[3]) // undefined

The spread operator

The spread operator is another feature introduced in ES6. It allows you to expand an iterable object into a list of arguments. It is very useful when you want to create a copy of an array or object or merge two arrays or objects.

JS
const animals = ['🐶', '🐱', '🐭', '🐹']
const birds = ['🐦', '🐧', '🦅', '🦆']

//The old way
const animalsAndBirds = animals.concat(birds)

//With spread operator ...
const animalsAndBirds = [...animals, ...birds]

Conclusion

By following these simple rules, you will make your code more readable and maintainable. And it will be easier for you and most importantly, other developers to understand your code. Keep in mind that these are just guidelines and not rules. You can always break them if you have a good reason to do so. That being said, keep on hacking! 🤓

Avatar of Ismayil Mirzayev with spray paint
July 24, 2023
Views: 65