6 Tips to create your javascript code looks clean and like a pro
If you are a new javascript programmer, you should know that writing clean codes is so important.
you should always try to make your code readable for every other programmer and even your future!! (believe me, the code you write and understand it now, is getting hundred times harder to read every day will past)
so follow this tree simple tricks to make your code more readable and cleaner.
1.IF TRUE & TURNARY OPERATORS
Bad code:
let isEmpty = true;
if (isEmpty == true) {
console.log('Empty')
}
else {
console.log('Is not empty')
}
Pro Code:
isEmpty ? console.log('Empty') : console.log('Is not empty');
2.DESCTRUCTUING
Bad Code:
const post = {
data: {
id:1,
title:'How to write codes like a pro',
text:'Just read this post until end'
}
}
const id = post.data.id;
const title = post.data.title;
console.log(id,title)
Pro code:
const {id,title} = post.data
console.log(id,title)
3.SHORT FOR LOOP
Bad code:
const cars = ['BMW I8','Audi R8','Pride 141']
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
Pro code:
for (let fruit of fruits) console.log(fruit);
4.ASSIGN VALUE IF EXISTS
Bad Code:
let port;
if (process.env.PORT) {
port = process.env.PORT
}
else {
port = 3000;
}
Pro Code:
let port = process.env.PORT || 3000
5.TEMPLATE LITERALS
Bad Code:
const name = 'Mehrab'
const portfolio_url= 'mehrab.xyz'
console.log('You can find ' + name + ' portfolio at ' + portfolio_url);
Pro Code:
console.log('You can find ${name} portfolio at ${portfolio_url}`);
6.OBJECT WITH IDENTICAL KEYS AND VALUES
Bad Code:
const user = {
name:name,
email:email,
phone:phone,
age:age
}
Pro Code:
const user = {name,email,phone,age}
and that’s it!
now you know 6 important tricks that make your code clean and like a pro.
don’t forget to use it in your codes ;)
Claps can be helpful too ❤️