First of all, what does clean coding mean?

Clean code is code that is easy to understand and easy to change.

OK, that sounds nice, but what does it mean? Easy to understand means the code is easy to read.

Why should you care about clean code?

You should care because the code is (almost) never written just once and then forgotten. Most of the time you, or someone else, need to work on that. You then need to decide when it is good enough and move on. Here is the JavaScript standard style guide.

JavaScript – Clean coding best practices

JavaScript uses two different types of equality operators: === | !== and == | !=

| and | When two operands are of the same type and have the same value, then === produces true and !== produces false.

These are some of the interesting cases:

'' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true

=== It checks the value with type. The example of it is given below.

For example:

var str = "300"; //This get execute if (str === "300") { alert("this alert get executed"); } //This does not execute if (str === 300) { alert("this alert not get executed"); }

== It does not check the value with type. The example of it is given below.

For example:

//This gets execute if (str == "300") { alert("this alert get executed"); } //This gets execute if (str == 300) { alert("this alert get executed"); }

2. Variables

2.1. Use meaningful and pronounceable variable names

Whenever you use a variable, a name of the variable should be useful and understandable for everyone.

Bad:

const yyyymmdstr = moment().format('YYYY/MM/DD');

Good:

const currentDate = moment().format('YYYY/MM/DD');

2.2. Do not add unneeded context

If your class/object name tells you something, do not repeat that in your variable name.

Bad:

const Car = { carMake: 'Honda', carModel: 'Accord', carColor: 'Blue' }; function paintCar(car) { car.carColor = 'Red'; }

Good:

const Car = { make: 'Honda', model: 'Accord', color: 'Blue' }; function paintCar(car) { car.color = 'Red'; // Use only car.color instead of car.carColor }

3. Function

Functions are one of the essential fundamental building blocks of JavaScript. To use it you must define it somewhere in the scope from which you wish to call.

3.1. Function arguments

A function should not have more than three arguments. Keep it as low as possible.

Bad:

function createMenu(title, body, buttonText, cancellable) { // ... }

Good:

function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true });

3.2. Function names should say what they do

If you create any function, function name should tell you the working of it. By doing this you can understand it in future, it helps you and your co-worker or anyone else.

Bad:

/** * Invite a new user with its email address * @param {String} user email address */ function inv(user) { /* implementation */ }

Good:

function inviteUser(emailAddress) { /* implementation */ }

3.3 Arrow function shorthand

Arrow functions are more compact and have shorter syntax than function expression, and it utilizes =>, that looks like a fat arrow.

Longhand:

function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });

Shorthand:

sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));

4. Shorthand for if

This might be trivial, but worth it. While doing if, assignment operators sometimes be omitted.

Longhand:

if (likeJavaScript === true) { // do something... }

Shorthand:

if (likeJavaScript) { // do something... }

Here is another example. If “a” is NOT equal to true, then do something.

Longhand:

let a; if (a !== true) { // do something... }

Shorthand:

let a; if (!a) { // do something... }

5. Object property shorthand

ES6 provides an even more natural way of assigning properties to objects. If the property name is the same as the key name, you can take advantage of the shorthand notation.

Longhand:

const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

6. Implicit return shorthand

We use return keyword to return the final result of a function. Arrow function with a single statement will return the result it’s evaluation. The function omits the braces {}. For use multi-line statement, it’s necessary to use () instead of {} to wrap your function body.

Longhand:

function calcCircumference(diameter) { return Math.PI * diameter; }

Shorthand:

calcCircumference = diameter => ( Math.PI * diameter; )

7. Declare variables outside of the for statement

While executing lengthy for statements, do not make the engine work any harder than it must. For example:

for (var i = 0; i < someArray.length; i++) { var container = document.getElementById('container'); container.innerHtml += 'my number: ' + i; console.log(i); }

Good:

var container = document.getElementById('container'); for (var i = 0, len = someArray.length; i < len; i++) { container.innerHtml += 'my number: ' + i; console.log(i); }

Having many global variables is always a bad thing because you can easily forget the name you declare of variable and you accidentally declare it somewhere else. Prevent global variables, because global variables are easily overwritten and it may lead maintenance issues.

Bad:

var name = 'Jeffrey'; var lastName = 'Way'; function doSomething() { … } console.log(name); // Jeffrey -- or window.name

Good:

var NameSpace = { name: 'Jeffrey', lastName: 'Way', doSomething: function() { ... } } console.log(NameSpace.name); // Jeffrey

9. Comment your code

Always comment your code it helps you to understand your own code. What happens when you return to the project months later, only to find that you cannot easily remember what your line of thinking was. Do not comment every small thing in your code. Just comment on things that have business logic complexity.

Bad:

function hashIt(data) { // The hash let hash = 0; // Length of string const length = data.length; // Loop through every character in data for (let a = 0; a < length; a++) { // Get character code. const char = data.charCodeAt(a); // Make the hash hash = ((hash << 5) - hash) + char; // Convert to 32-bit integer hash &= hash; } }

Good:

function hashIt(data) { let hash = 0; const length = data.length; for (let a = 0; a < length; a++) { const char = data.charCodeAt(i); hash = ((hash << 5) - hash) + char; // Convert to 32-bit integer hash &= hash; } }

9.1. Do not leave commented out code in your codebase

If there is code which you no longer wanted do not comment it, remove it from the code.

Bad:

doStuff(); // doOtherStuff(); // doSomeMoreStuff(); // doSoMuchStuff();

Good:

doStuff();

10. Do not pass a string to “setInterval” or “setTimeOut”

Consider the following code:

setInterval("document.getElementById('container').innerHTML += 'My new number: ' + i", 3000);

Pass a function name instead of passing a string to setInterval and setTimeOut.

setInterval(someFunction, 3000);

11. Use consistent capitalization

JavaScript is untyped, so capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just be consistent.

Bad:

const DAYS_IN_WEEK = 7; const daysInMonth = 30; const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; function eraseDatabase() { //... } function restore_database() { //... } class animal { //... } class Alpaca { //... }

Good:

const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30; const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles']; function eraseDatabase() { //... } function restoreDatabase() { //... } class Animal { //... } class Alpaca { //... }

12. How to write nice async code?

Use Promise, instead of using nested callbacks. You can use chainable promise calls.

Avoid:

asyncFunc1((err, result1) => { asyncFunc2(result1, (err, result2) => { asyncFunc3(result2, (err, result3) => { console.log(result3) }) }) })

Prefer:

asyncFuncPromise1() .then(asyncFuncPromise2) .then(asyncFuncPromise3) .then((result) => console.log(result)) .catch((err) => console.error(err))

13. Do not repeat yourself

If you are doing the same thing in multiple places, consolidate the duplicate code. Here is the example of Reactjs.

Dirty:

const MyComponent = () => ( <div> <OtherComponent type="a" className="colorful" foo={123} bar={456} /> <OtherComponent type="b" className="colorful" foo={123} bar={456} /> </div> );

Clean:

const MyOtherComponent = ({ type }) => ( <OtherComponent type={type} className="colorful" foo={123} bar={456} /> ); const MyComponent = () => ( <div> <MyOtherComponent type="a" /> <MyOtherComponent type="b" /> </div> );

In conclusion…

I hope that I have helped you to see the benefits and advantages of writing good clean code. You can even use some of the examples presented here.