Good Way to Program with JavaScript — Part 1
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.
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 :
Good Practice
Within console we can print multiple object variable like —
console.log({obj1, obj2, …})
But if this data is more important so we can use custom css Styling, Syntax —
console.log(‘%c Message =>’, ‘normal css code here ’);
One thing we notice if objects have same properties so we can also console in tabular form —
console.table(); // For similar kind object property
Calculating how much time take your Code to be execute ?
console.time(‘looper’) ; // where start
//Here Write your JS CODE
console.timeEnd(‘looper’)
Example —
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
2. Destructuring —
we should not write redundatnt code like in given example using — bird.name, bird.color , …. so we destructure code like —
Output —
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
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.collegestudent[‘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.
After ES6 —
Use Array Built In Methods.
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 —
Using Promise we have .then callback hells so now async/await comes in picture.
Async/Await allows us express asynchronous code in synchronous manner.
- 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;
}
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.