Some Js clean code tips

alwarg

Alwar G

Posted on June 8, 2020

Some Js clean code tips

Hi Everyone,

Today i am going to tell about some js clean code tips based on code readablity not on performance

1) No continuous object properties assign:

 let obj = {};
 obj.a = '1';
 obj.b = '2';
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

Object.assign(obj, { a: '1', b: '2' });
Enter fullscreen mode Exit fullscreen mode

2) Use object destructuring in function arguments:

    function print(obj) {
     console.log(obj.a);
    }
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

   function print({ a }) {
     console.log(a);
    }
Enter fullscreen mode Exit fullscreen mode

3) No unneeded ternary:

  let a = b === 10 ? true : false;
  let c = d ? true : false;
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

  let a = b === 10
  let c = !!d
Enter fullscreen mode Exit fullscreen mode

lint rule is https://eslint.org/docs/rules/no-unneeded-ternary

4) No repeated if check:

  if(cond1) {
     if(cond2) {
        // do something
     }
  }
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

if(cond1 && cond2) {
   // do something
}
Enter fullscreen mode Exit fullscreen mode

5) No unneeded boolean return:

 function getBoolean() {
  if(cond) {
     return true;
  }
  return false;
 }
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

function getBoolean() {
   return cond;
}
Enter fullscreen mode Exit fullscreen mode

6) Converge object destructuring:

  let { prop1 } = obj;
  let { prop2 } = obj;
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

  let { prop1, prop2 } = obj;
Enter fullscreen mode Exit fullscreen mode

7) No Duplicate Imports:

  import { a } from 'filepath';
  import { b } from 'filepath';
Enter fullscreen mode Exit fullscreen mode

We can write the above code as

  import { a, b } from 'filepath';
Enter fullscreen mode Exit fullscreen mode

lint rule is https://eslint.org/docs/rules/no-duplicate-imports

I hope you enjoyed this post. Thanks for reading.

Source documentation is https://github.com/airbnb/javascript

💖 💪 🙅 🚩
alwarg
Alwar G

Posted on June 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related