Good Way to Program with JavaScript — Part 1

Shivam Gupta
5 min readNov 19, 2018

--

Javascript is a programming language that people loves a lot , in old times developers pride themself for being backend developer and think front end just very simple task. but its 2019 coming and we have now tools and API like aws, doc, twillo, stripe, cloud, docker etc.

Front End APIs & tools

You can now develop Front End + Back End also with many open source website with JavaScript.

Here I will Discuss about writing good javascript with modern features and avoid writting Bad javaScript.

1. How To Debug your javaScript like a Pro —

Using console.log :

Bad Practice: multiple object with multiple console

Good Practice

Within console we can print multiple object variable like —

console.log({obj1, obj2, …})

use object pattern in console

But if this data is more important so we can use custom css Styling, Syntax —

console.log(‘%c Message =>’, ‘normal css code here ’);

Bold Red — Style for message

One thing we notice if objects have same properties so we can also console in tabular form —

console.table(); // For similar kind object property

Objects with same property should be console in Tabular Form

Calculating how much time take your Code to be execute ?

console.time(‘looper’) ; // where start

//Here Write your JS CODE

console.timeEnd(‘looper’)

Example —

Example — Console.time

How to know from where console.log originating —

lets think we have a important method deleteData() , it deletes data from database and make sure dont call this method twice so how to know ?

console.trace(‘delete call ! ’);

a. It will tell where the function is define

b. from which line of code, it called

We can trace Definition and Calling Line

2. Destructuring —

we should not write redundatnt code like in given example using — bird.name, bird.color , …. so we destructure code like —

Bad Code vs Destructured code

Output —

Good Practice — Destructure Object

3. Template String literals over concatenate String by +

So to use template literal use backTick operater ` and to append variable use ` Hello $ {variable} . This is very Cleaner way to write code

Doing it Purely Functional Way —

We can call any function without Paranthesis just use `` => template literals pattern.

function callMe(call, count) {
console.log(‘call =>’, call, ‘count =>’, count)
}

Output-

callMe`Hey ${1+1}`
VM367:2 call => (2) [“Hey “, “”, raw: Array(2)] count => 2

Example- Template String way to call method , this pattern use by- Polymer

3. Spread Syntax to work with Object and Arrays

We have 2 objects —

const student = {name: ‘Shivam’} // obj1
const stats = {college: ‘XYZ College’, hobby: [‘Technology’, ‘Cricket’]} // obj2

Now we need a common object for both
a) Bad Style of coding

const student = {name: ‘Shivam’}
const stats = {college: ‘XYZ College’, hobby: [‘Technology’, ‘Cricket’]}

/* Now Create a common Object => Bad practice */
student[‘college’] = stats.college

student[‘hobby’] = stats.hobby

b) Better Way —

const student = {name: ‘Shivam’}
const stats = {college: ‘XYZ College’, hobby: [‘Technology’, ‘Cricket’]}

// Now Create a common Object

//Good Practice
const common = Object.assign(student, stats) // it will merge 2 object from left to right

But we can make it more easy Way using spread operater —

const common= {…student, …stats}

for merging single key with an existing object-

const obj1 = {name: ‘shivam’, age: 24}

const obj2 = {…obj1, profession: ‘Software Engimeer’}

We can also use spread operater to Array —

const data = [‘Shivam’]

// Bad Array Code
data.push(‘Ankit’)
data.push(‘Anjali’)

console.log(‘DATA => ‘, data) // append after shivam

Better way to do this with spread operater —

const data = [‘Shivam’]

data= […data, ‘Ankit’, ‘Anjali’]

We can also append from Last (unshift)

data = [‘Ankit’, ‘Anjali’, …data]

O/P —
[“Ankit”, “Anjali”, “Shivam”]

Appending in middle —

data = [‘Ankit’, …data, ‘Shivam’]

4. Loops

We have an array we need to calculate — total of elements , modify all Array , and filter out some of elements.

Old loop way

After ES6 —

Use Array Built In Methods.

Using- Reduce, Filter and map

5. Using Async Await —

Suppose we have 3 asynchronous calls (Ex. api calls or something else) and we want to use all of three async call data together. Means how we handle multiple asynchronous calls better way ?

Lets Create a method random, it returns a promise that resolve a random number. Now imagine we want to retreive 3 different asynchronous number and sum these three numbers by a method.

const random = () => {
return Promise.resolve(Math.random())
}

Using Promise Chain —

Multiple Async data using together by Promise

Using Promise we have .then callback hells so now async/await comes in picture.

Async/Await allows us express asynchronous code in synchronous manner.

  1. Write async keyword before the function which consist promises

const sumAsyncNumbers = async() => {

}

2. Use await keyword in front of promises

const sumAsyncNumbers = async() => {

const first = await random();

const second = await random();

const third = await random();

return first + second + third;

}

Make Promise call Synchronous if — 1 promise depend to another

So Using Async await make Asynchronous coede in synchronous manner like untill 1 promise not resolved await keyword will make wait then next line will be execute.

We can also do some cool stuff with await like —

if(await(random)) {

}

const randos = Promise.all([

random(),

random(),

random()

])

// Looping async Items

for(const r of await randos) {

}

Thanks for reading, if this post help you so do claps and give suggestions and comments.

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

No responses yet