Tricks to write less JavaScript
1.IF TRUE & TURNARY OPERATOR
let isEmpty = true;
if(isEmpty == true) {
console.log('Empty');
} else {
console.log('Is not Empty');
}
isEmpty ? console.log('Empty') : console.log('Is not empty')
2.SHORT FOR LOOP
const fruits = ['mango','apple','banana'];
for(let i = 0; i < fruits.length; i++) {
const fruit = fruits[i];
console.log(fruit);
}
for(let fruit of fruits)console.log(fruit);3.DESTRUCTURING
const post = {
data: {
id: 1,
title: 'post 1'
text: 'Hello world'
author: 'Scalipsum',
},
};
const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.author;
const {id, title,text,author} = post.data;
console.log(id,title,text,author);
4.OBJECTS WITH IDENTICAL KEYS AND VALUES
const userDetails = {
name: name, //'name' key = 'name' variable
email: email
age: age,
location: location,
};
const userdetails = {name,email,age,location};
5.TEMPLATE LITERALS
const name ='w3technology'; const timeofDay ='afternoon'; const greeting = 'Hello ' + name + ', I wish you a good' + timeofDay + '!';
const greeting = 'Hello ${name}, I wish you a good ${timeofDay}!';
5.ASSIGN A VALUE IF EXISTS
let port;
if(process.env.PORT){
port = process.env.PORT;
}else{
port = 5000;
}
let port = process.env.PORT || 5000;
No comments: