DEV Community

Mohammad Faisal
Mohammad Faisal

Posted on • Edited on • Originally published at mdfaisal.com

15 Rules For Writing Clean JavaScript

To read more articles like this, visit my blog

So you are a React developer or Node.js developer. You can write code that works. But can you write code that is visually beautiful and understandable by others?

Today we will see some rules to make your JavaScript code clean and clear.

Rule 1. Don’t Use Random Characters as Variable

Don’t use some random character to express a variable.

//BAD 

const x = 4;
Enter fullscreen mode Exit fullscreen mode

Name your variable properly so that it describes the value properly.

//GOOD

const numberOfChildren = 4;
Enter fullscreen mode Exit fullscreen mode

Rule 2. Use camelCase Variable Name

Don’t use snake_case, PascalCase, or a variable name that starts with a verb.

// Bad: Begins with uppercase letter 

var UserName = "Faisal"; 

    -----

// Bad: Begins with verb 

var getUserName = "Faisal"; 

    -----

// Bad: Uses underscore 

var user_name = "faisal";
Enter fullscreen mode Exit fullscreen mode

Instead, use a camel-cased variable name that represents a noun.

// Good

const userName = "Faisal";
Enter fullscreen mode Exit fullscreen mode

Rule 3. Use Good camelCase Function Name

Don’t use any noun as a function name to avoid confusion with the variable names.

// Bad: Begins with uppercase letter 
function DoSomething() {  
    // code 
} 

    ----

// Bad: Begins with noun 
function car() {  
    // code 
} 

    ----

// Bad: Uses underscores 
function do_something() {  
    // code 
}
Enter fullscreen mode Exit fullscreen mode

Instead, start the name with a verb and use camel case.

//GOOD

function doSomething() {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Rule 4. Use PascalCase For Constructor Function Naming

// Bad: Begins with lowercase letter 
function myObject() {  
    // code 
} 

    ----

// Bad: Uses underscores 
function My_Object() {  
    // code 
} 

    ----

// Bad: Begins with verb 
function getMyObject() {  
    // code 
}
Enter fullscreen mode Exit fullscreen mode

Also, Constructor function names should begin with a nonverb because new is the action of creating an object instance.

// GOOD

function MyObject() {  
    // code 
}
Enter fullscreen mode Exit fullscreen mode

Rule 5. Global Constants

Global constants whose value doesn't change should not be named like normal variables.

// BAD

const numberOfChildren = 4;

// BAD 

const number_of_children = 4;
Enter fullscreen mode Exit fullscreen mode

They should be all upper case and separated with underscores.

// GOOD

const NUMBER_OF_CHILDREN = 4;
Enter fullscreen mode Exit fullscreen mode

Rule 6. Assignment to Variable

Don’t assign a comparison value to a variable without parentheses.

// BAD 

const flag = i < count;
Enter fullscreen mode Exit fullscreen mode

Use parentheses around the expression:

// GOOD

const flag = (i < count);
Enter fullscreen mode Exit fullscreen mode

Rule 7. Usage of Equality Operators

Don't use “==” or “!=” to compare values. Because they don't type check before comparison.

//BAD

if (a == b){
    //code
}
Enter fullscreen mode Exit fullscreen mode

Instead, always use “===” or “!==” to avoid type coercion errors.

//GOOD

if (a === b){
    //code
}
Enter fullscreen mode Exit fullscreen mode

Rule 8. Usage of the Ternary Operator

Don’t use the ternary operator as an alternative to if statement:

//BAD

condition ? doSomething() : doSomethingElse();
Enter fullscreen mode Exit fullscreen mode

Only use them to assign values based on some condition:

// GOOD

const value = condition ? value1 : value2;
Enter fullscreen mode Exit fullscreen mode

Rule 9. Simple Statement

Although JavaScript supports it. Don’t write multiple statements in a single line.

// BAD

a =b; count ++;
Enter fullscreen mode Exit fullscreen mode

Instead, have multiple lines for multiple statements. And always use a semicolon at the end of a line.

// GOOD

a = b;
count++;
Enter fullscreen mode Exit fullscreen mode

Rule 10. Use of If Statements

Don’t omit the braces from an if statement and never keep them in a single line.

// BAD: Improper spacing 
if(condition){  
    doSomething(); 
} 

    ----

// BAD: Missing braces 
if (condition)  
    doSomething(); 

    ----

// BAD: All on one line 
if (condition) { doSomething(); } 

    ----

// BAD: All on one line without braces 
if (condition) doSomething();
Enter fullscreen mode Exit fullscreen mode

Always use braces and proper spacing:

// GOOD

if (condition) {
    doSomething();
}
Enter fullscreen mode Exit fullscreen mode

Rule 11. Usage of For Loop

Don’t declare the variable in the initialization of a for loop.

// BAD: Variables declared during initialization 

for (let i=0, len=10; i < len; i++) {  
    // code 
}
Enter fullscreen mode Exit fullscreen mode

Declare them before the loop.

// GOOD

let i = 0;

for (i=0, len=10; i < len; i++) {  
    // code 
}
Enter fullscreen mode Exit fullscreen mode

Rule 12. Consistent Indentation Length

Stick to using 2 or 4 all the time.

// GOOD

if (condition) {
    doSomething();
}
Enter fullscreen mode Exit fullscreen mode

Rule 13. Line Length

Any line should not be more than 80 characters. If it’s more than that they should be broken up into a new line.

// BAD: Following line only indented four spaces doSomething(argument1, argument2, argument3, argument4,
    argument5); 

    ----

// BAD: Breaking before operator 
doSomething(argument1, argument2, argument3, argument4
        ,argument5);
Enter fullscreen mode Exit fullscreen mode

The second line should be indented **8 spaces **instead of 4 and shouldn't start with a separator.

// GOOD
doSomething(argument1, argument2, argument3, argument4,
        argument5);
Enter fullscreen mode Exit fullscreen mode

Rule 14. Primitive Literals

Strings shouldn’t use a single quote.

// BAD

const description = 'this is a description';
Enter fullscreen mode Exit fullscreen mode

Instead, they should always use double-quotation

// GOOD

const description = "this is a description";
Enter fullscreen mode Exit fullscreen mode

Rule 15: Use of “undefined”

Never use the special value undefined.

// BAD

if (variable === "undefined") {  
    // do something 
}
Enter fullscreen mode Exit fullscreen mode

To see if a variable has been defined, use the typeof operator

    // GOOD

    if (typeof variable === "undefined") {  
        // do something 
    }
Enter fullscreen mode Exit fullscreen mode

So by following these rules, you can make your JavaScript projects cleaner.

These rules are taken from the book “Maintainable Javascript” written by “Nicholas C. Zakas”. So if you don’t agree with some of the points, I guess that’s fine. When it comes to styling there is no single way. But the rules here can be a good starting point for you.

That’s it for today. Happy Coding! :D

Get in touch with me via LinkedIn or my Personal Website.

Top comments (15)

Collapse
 
axel_nieminen_072275fab50 profile image
niemax

Great article! From my perspective the usage of if statements on one line is very clear if the condition and the function have declarative names. I often omit the braces if I'm sure it's easy to read. :)

Collapse
 
dvalin99 profile image
Domenico Tenace

Nice article!
I have one more point, in my opinion, that would help to write clean code in JavaScript:

Use a maximum of two input parameters for functions.

For me, this is a good helper to write clean code and visually helps to understand the code better.
What do you think?

Collapse
 
mohammadfaisal profile image
Mohammad Faisal

Totally agree. Although I would go upto 3 parameters.

Collapse
 
itsahsanmangal profile image
Ahsan Mangal 👨🏻‍💻

This rticle is well-organized and straightforward, presenting 15 distinct rules, each with its own "bad" and "good" examples.

Collapse
 
himanshudevgupta profile image
Himanshu Gupta

Such a good article @mohammadfaisal thank you for sharing

Collapse
 
mohammadfaisal profile image
Mohammad Faisal

Thank you!

Collapse
 
matborowiak profile image
Mat Borowiak

What do you think about one-liner guards inside functions? These also stack nicely. Eg:

const myFunction = (name) => {
   if (shouldStop) return;
   if (alsoShouldStop) return;

   const changedName = changeName(name);
   return changedName;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jackmellis profile image
Jack

Very few of these rules come with any actual explanation.
Some of them do have an important purpose (consistent variable casing means a developer from any language/codebase can quickly identify classes/variables/constants, for example), but lots of these rules are purely personal preference.
I think you'd find a lot of these difficult to justify other than "that's how I do it", "it said so in a book", or "because prettier"

Collapse
 
mohammadfaisal profile image
Mohammad Faisal

Maybe. But is there any universal styleguide for javascript? I guess not.
So every style guideline will ultimately fall into the "personal pereferance" bucket

Collapse
 
jackmellis profile image
Jack

There are a few "standard" rulesets for eslint, and there's prettier, but ultimately there are a lot of personal preferences - which are absolutely fine to have. However, there's a big difference between personal stylistic preferences, and practices that are intended to reduce bugs/errors.

Collapse
 
balazssoltesz profile image
Balazs Soltesz

Or in one sentence: use eslint

Collapse
 
mohammadfaisal profile image
Mohammad Faisal

Eslint is a tool that helps to apply the knowledge with ease.

Eslint is not the knowledge.

Collapse
 
edmundasramanauskas profile image
Edmundas Ramanauskas • Edited

sorry if this sounds offensive (I'm not trying to be) but neither is your post.
you wrote 15 rules but didn't explain why they're good.
also, I would like to know you're reasoning regarding points 11 and 14.
I've never seen 11 in action unless you have 2 loops in a row and want to reuse variable.
regarding 14, I've seen people using both and never had any problem myself with either. and personally I prefer using single quotes because if you need to put html or json inside the string you don't need to escape it.
point 15 is just comparing apples to potatoes. it's just a mistake and no linter will help you here. so it shouldn't be in the list because you're just saying don't make this particular mistake and it has nothing to do with coding style or rules. unless you made a mistake yourself and actually meant variable === undefined instead in which case it warrants an explanation.

Thread Thread
 
mohammadfaisal profile image
Mohammad Faisal

I understand your point. These rules are taken from the book “Maintainable Javascript” written by “Nicholas C. Zakas”.

So obviously we will not agree on all the points. Because style is subjective.

Collapse
 
poljeff profile image
Pol Jeff

I disagree with rules 11 and 14