It easy to code in JavaScript but difficult to write quality code in JavaScript. JavaScript has come a long way from being a tool to write in-browser animations. It is now used everywhere, frontend, backend even desktop native applications. If you are developing web applications, there are a lot of chances that you are probably using JavaScript.  It is the most widely used language in the world according to Stack Overflow survey. With hundreds of frameworks, it certainly has the support of the community as well. But then what is wrong with it??
Well, the worst thing about JavaScript is that it is too verbose.  It is weakly typed and tries to do a lot under the hood which makes it pretty confusing. The number of variants and ECMA syntax releasing year after year provides so many options that the code becomes too difficult to understand, refractor and scale.

In this article, we discuss some standards which if followed/used can make the code quality little better. Let’s go along…

1)Debug Statements:

The most obvious way of debugging for most of the developers out there is obviously console.log statement. It just prints whatever argument you pass into it on the console or terminal (in case of node js). But there are various cool ways to use console statements which can drastically decrease the time and efforts you put into debugging. Let us suppose we have three fruits (mango, apple, and grapes) as an object which have some properties. The trivial way to see the value of attributes of each fruit will be simple consoling out the fruit name.

let mango = {color:"yellow" , taste: "sweet", season: "summers"};
let apple = {color: "red" , taste: "sweet", season : "all"};
let grape = {color: "green", taste:"sweet", season: "winters"};

This piece of code produces the following output:

 

We now have to make two more similar calls to console.log in order to get the value of their attributes. We can make a little tweak in here to console the attributes of all the objects in one call to console.log.

console.log({mango, apple, grape});

And this is the outcome of this simple tweak, all the attributes in one go.

 

However, there is an even neater technique to console the attributes of objects with similar properties. Just use console.table(),

console.table([mango, grape, apple]);

Which gives you a very neat way to view and compare all the properties of objects. Easy to look, easier to debug.

2) Template Literals

Creating a string with some dynamic content is one of the primary requirements. Mango is yellow, has a sweet taste and is available in summers. Apple is red, sweet in taste and is available in winters. If you read these two sentences you see that the skeleton of the string is same, just the attributes and entity has changed from mango to apple. For any person who has even a bit of experience in programming, this seems to be a straight forward application of string concatenation. The most general solution of this sort of a problem shall be:

 

function str(fruit, name) {
    return name+"is" + fruit.color + "in color, has a "+ fruit.taste +"taste and is available in "+ fruit.season";
}
str(mango, "Mango"); // Mango is yellow in color, has a sweet tase and is available in summers

Although working, the solution is far from neat,  increase the number of attributes and you will see how quickly that sign becomes a mess. JavaScript provides template literals to solve the day. Template literals allow string formatting in a very neat and intuitive way. Here is the solution of the same problem in string formatting way:

 

function str(fruit, name) {
    return `${name} is ${fruit.color} in color, has a ${fruit.taste} taste and is available in ${fruit.season}`;
}
str(mango, "Mango"); // Mango is yellow in color, has a sweet tase and is available in summers

 

Thus we see, using $ as a way to show a variable and {} as placeholders, we were able to format string in a very nice and intuitive way.

3) Destructuring:

This is a technique in which we breakdown the objects into their attributes and use them in our code. Suppose we are formatting a sentence with the above-declared fruit object, if we use the dot notation (mango.color), we shall have to use the mango three times to print the whole sentence.


s = Mango is ${mango.color} in color, has a ${mango.taste} taste and is available in ${mango.season}

A better way to do this will be using destructuring. We will break mango object into three different objects whose name will be exactly the same as the properties of the object mango.

function ex({color, taste, season}) {
   return Mango is {$color} in color, has a {$taste} taste and is available in {$season}
}

s = ex(mango);

 

We see here how easy it becomes to access the properties of an object using destructuring.

 

4) Spread Syntax

The spread syntax is a very clean and intuitive way to merge two objects into another object or two merges to two objects into another array. Let’s look at an example. 

Suppose we have one more object as follow :


details = {cost : 10, available: true}

This gives us details about the fruit mango. Now we want to make a single object that contains both the properties and details of mango. Let’s see how a naive approach will look like:

mango['cost'] = details.cost
mango['available'] = details.available

This approach caters to the problem alright, but just imagine if we had hundreds of such properties, doing so would have been a tedious job. Now let’s explore the power of spread syntax.


mango = {...mango, ...details}
console.log(mango); //{color:"yellow", taste:"sweet", season: "summers", cost:10, available:true}

The symbol (…) is called the spread symbol. Similarly, spread syntax can also be used for concatenating two arrays. Although you can live without this operator, its use does contribute to writing g quality code in javascript.

 

We will be discussing more approaches like async/await pattern, array functions, etc in the next part of the series. Till then try to use these tricks and hack them further to suit your specific needs and always try to write good quality javascript code.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

Wordpress Social Share Plugin powered by Ultimatelysocial
error

Enjoy this blog? Please spread the word :)