improve JavaScript coding

JavaScript is one of the most popular programming languages across the globe. With the release of Nodejs in 2009 and Modern UI frameworks like React, Vue, ML libraries like TensorFlow, we can develop any Web, Mobile and AI application. It’s always good to keep a certain coding standard while writing any program.

Improve JavaScript Coding

Having been a developer for over a decade, I firmly believe that a certain discipline and adhering to a basic set of standards always keep what you are building robust, clean and easily manageable. Here are my 5 best practices to improve your JavaScript coding standards.

1) Destructure

Destructuring is an efficient way to access data from the object. It helps you to convert object properties into distinct variables. If you are accessing the properties of an object in multiple places, destructuring will help to reduce your code and it will make your code more readable and manageable. You can even pass arguments to function as an object instead of variables. Then, destructure them in your function.

function getUserDetails(user){
     console.log(`User Name: ${user.name}`);
     console.log(`User Email: ${user.email}`);
     console.log(`User Age: ${user.age}`);
     console.log(`User City: ${user.city}`);
}

In the above code, we are printing the user’s details and there is nothing wrong with this code. But here we are repeatedly accessing user object. That means more code. By destructuring user object, we will be able to reduce those repetitive codes.

function getUserDetails({name, email, age, city}){
     console.log(`User Name: ${name}`);
     console.log(`User Email: ${email}`);
     console.log(`User Age: ${age}`);
     console.log(`User City: ${city}`);
}

2) Array

Array is the most widely used in any programming language and it is the same with JavaScript. Managing arrays is one of the crucial parts of application development. Since unwanted arrays or loops can heavily affect the performance of your application, following are some tips or practices that you keep in your mind while writing any array related code.

  • Don’t use loops for copying normal array or objects array. Use spread operator (…) instead.
  • Spread operators is not always a best option for every problems. Like, for mapping over iterables use Array.from because it avoids creating an intermediate array.
  • Use for loops instead of forEach if you want to perform any task that requires await.
  • Instead assigning item directly like ‘newArray[i] = users[i]’, use push method
// Not This
let length = users.length
let newArray = []
for(let i = 0; i < length; i++){
    // Not This
    newArray[i] = users[i]
    // Try This
    newArray.push(users[i])
}

// Try This
let newArray = [...users]

3) Object

Like arrays, object is also common in JavaScript programming. An object is a collection of properties, and a property is an association between key and value. Try to follow these while writing objects.

  • Use for…in loop to traverses all enumerable properties of an object and its prototype chain.
  • Use Object.keys() to return all object keys as an array.
  • If you are assigning a variable as a property value and if the variable name and property are same, you can use shorthand. Keep all your shorthand properties together for better readability.
let name = 'Nithin';
let email = 'mail@me.com'

// Not This
let userDetails = {
    name:name,
    age:30,
    email:email,
    city:'Bangalore'
}

// Try This
let userDetails = {
    name,
    email,
    age:30,
    city:'Bangalore'
}
  • Do not call Object.prototype methods directly
// Not This
console.log(userDetails.hasOwnProperty(name))

// Try This
const has = Object.prototype.hasOwnProperty;
console.log(has.call(userDetails, name));
// or Use has npm package

4) Arrow Function

Arrow function is one of the major updates that happened in ES6. With the help of the arrow function, we can shorten our function code. If the function has only one statement, and the statement returns a value, we can even remove the brackets and the return keyword.

// Old way
array.map(function (name) {
 return 'Name ' + name;
});

// With arrow function
array.map((name) => {
 return 'Name ' + name;
});

// For single statement Not This
const greet = (name) => {
  return `Hello ${name}`;
}

// Try This
const greet = (name) => `Hello ${name}`;
  • Avoid using arrow function syntax => with comparison operators like <= or >=
// Not This
const isMinor = (age) => age <= 18;

// Try This
const isMinor = (age) => {
 return age <= 18;
}
  • Always use parentheses around parameter
// Not This
array.map(item => {
  return 'Name ' + item;
});

// Try This
array.map((item) => {
  return 'Name ' + item;
});

5) Variables

Declaring variables is not a big deal in JavaScript. Till 2015 it was pretty much straightforward, just declare it with var. But in 2015 JS introduced two more keywords let and const. Keep in mind, if you want to run your code in old browsers use var. Use const for constant variable and let for others. Few things to take care of while working with variables in JavaScript.

  • Group all your const, let and var variables together, don’t mix it.
  • You can define all your const or let variable together with comma. For better readability define it seperate.
// Not This
const name = 'Nithin',age=30,email = mail@me.com

// Try This
const name = 'Nithin';
const age=30;
const email = mail@me.com
  • Define variable only if you need or using them
//Not This
function getDetails(status){
  const userDetails = getUserInfo()
  if(status == 'active'){
      return userDetails;
  }else{
      return false;
  }
}

// Try This
function getDetails(status){
  if(status != 'active'){
     return false;
  }
  const userDetails = getUserInfo()
  return userDetails;
}
  • Avoid linebreaks before or after = in an assignment. If its long, surround the value in parens
  • Avoid using unary increments and decrements ++ or —. As per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application.
//Not This
num++ or --num

//Try This
num += 1 or num -= 1

I hope you got some helpful tips to improve JavaScript coding from this article. If so, please share it with your circle and leave any comments if you want to add on these.

<> Happy Coding </>

Leave a Reply

Your email address will not be published.