Codementor Events

7 Best Practice to write clean JavaScript Code

Published Jan 22, 2021
7 Best Practice to write clean JavaScript Code

In this article i will explain some javascript snippent to write clean code.
Note:
This all code written in JavaScript Code.

1.Desclare and Assign Variable using array indexes

Before

let first = arr[0];
let second = arr[1];

After

let [first,second] = arr;

This is helpful if arr elements are equal to variables that we have declared.

2. Use Logical Operator for simple conditions

Before

if (isTrue) {
  toDoFunction();
}

After

isTrue && toDoFunction(); 

This is very simple way to ignore if condition but most of the developer don't know how to overcome code by this statement.

3. Paasing a parameter conditionally.

Before

if(!check){
name='Rizwan';
}
setName(name);

After

setName(name || 'Rizwan'); 

This statement means that if name is false then assign value to it otherwise not.

4. Deals with many Zero's (0's)

Before

const weight=45000000000; 

After

const weight=45e9
put number of zero's after e ,which mean that "45 raise to the power of 9".

5. Assign same value to multiplr variables

Before

a;
b=a;
c=a;
> After 
c=b=a=4;

The above statement is look very simple, same value will be assigned to each variable.

6. Use ternary operator in correct way

Before

a > b ? name = 'Muhammad' : name='Rizwan';

After (Correct Way)

name = a > b ? 'Muhammad' : 'Rizwan';

Must check the condition with ternary operator.

7. Export many variables

Before

export let a;
export let b;
export let c;

After

 export let a,b,c;

Thank you For reading this article hope you have learned and hope it will help you in your daily life coding,
Mention your opinion about it
and write the short snippet which you are using routinely in coding.

Discover and read more posts from Rizwan
get started