Tricks to write less JavaScript

Fahim Ahammed Firoz
2 min readMay 3, 2021

1. if true and ternary operator

let isEmpty = true;
if(isEmpty === true){
console.log(‘Empty’);
}else{
console.log(‘Not Empty’);
}

isEmpty ? console.log(‘Empty’) : console.log(‘Not Empty’);

2. Destructuring

const post = {
data: {
id: 1,
title: ‘Hello’,
text: ‘Hello World’,
author: ‘Fahim Ahammed’
}
}

const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.text;
console.log(id, title, text, author);

const {id, title, text, author} = post.data;
console.log(id, title, text, author);

3. Short for loop:

const fruits = [‘Mango’, ‘Banana’, ‘Orange’, ‘Apple’];
for(let i=0; i<fruits.length; i++){
console.log(fruits[i]);
}

for(let fruit of fruits)
console.log(fruit);

4. Assign a value if exists:

let port;
if(process.env.PORT){
port = process.env.PORT;
} else{
port = 5000;
}

let port = process.env.PORT || 5000;

5. Template Literals:

const name = ‘Fahim’;
const timeOfDay = ‘night’;
const greeting = ‘Hello’ + name + ‘I wish you a good’ + timeOfDay + ‘!’;

const greeting = `Hello ${name}, I wish you a good ${timeOfDay} !`;

6. Object with identical keys and values:
const userDetails = {
name: name,
email : email,
age: age,
location: location
};

const userDetails = { name, email, age, location };

7. Declaring Variables

//Longhand
let x;
let y;
let z = “post”;

//Shorthand
let x, y, z = “post”;

8. Assignment Operator

//Longhand
x = x + y;
x = x — y;

//Shorthand
x += y;
x -= y;

9. Arrow Function

//Longhand
function sayHello(name) {
console.log(“Hello”, name);
}

list.forEach(function (item) {
console.log(item);
});

//Shorthand
sayHello = name => console.log(“Hello”, name);

list.forEach(item => console.log(item));

10. Object Array Notation

//Longhand
let arr = new Array();
arr[0] = “html”;
arr[1] = “css”;
arr[2] = “js”;

//Shorthand
let arr = [“html”, “css”, “js”];

--

--

Fahim Ahammed Firoz

I am a hardworking, confident, enthusiastic Web developer and I want to utilize my knowledge and personal skills in Web Development.