9 Tricks To Write Less JavaScript.
Shoaib Sayyed
Posted on May 7, 2020
Hi Dev π, Thanks for opening my blog. I hope you are doing well and ready to learn some Tricks To Write Less JavaScript π.
So, let's start!
1. Declaring Variables
//Longhand
let x;
let y;
let z = "post";
//Shorthand
let x, y, z = "post";
2. Assignment Operator
//Longhand
x = x + y;
x = x - y;
//Shorthand
x += y;
x -= y;
3. Ternary Operator
let answer, num = 15;
//Longhand
if (num > 10) {
answer = "greater than 10";
}
else {
answer = "less than 10";
}
//Shorthand
const answer = num > 10 ? "greater than 10" : "less than 10";
4. Short for Loop
const languages = ["html", "css", "js"];
//Longhand
for (let i = 0; i < languages.length; i++) {
const language = languages[i];
console.log(language);
}
//Shorthand
for (let language of languages) console.log(language);
5. Template Literals
const name = "Dev";
const timeOfDay = "afternoon";
//Longhand
const greeting = "Hello " + name + ", I wish you a good " + timeOfDay + "!";
//Shorthand
const greeting = `Hello ${name}, I wish you a good ${timeOfDay}!`;
6. 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));
7. Object Array Notation
//Longhand
let arr = new Array();
arr[0] = "html";
arr[1] = "css";
arr[2] = "js";
//Shorthand
let arr = ["html", "css", "js"];
8. Object Destructuring
const post = {
data: {
id: 1,
title: "9 trick to write less Javascript",
text: "Hello World!",
author: "Shoaib Sayyed",
},
};
//Longhand
const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.author;
//Shorthand
const { id, title, text, author } = post.data;
9. Object with identical Keys and Values
//Longhand
const userDetails = {
name: name, // 'name' key = 'name' variable
email: email,
age: age,
location: location,
};
//Shorthand
const userDetails = { name, email, age, location };
That's It π.
Thanks for reading! My name is Shoaib Sayyed; I love helping people to learn new skills π. You can follow me, if youβd like to be notified about new articles and resources.
π πͺ π
π©
Shoaib Sayyed
Posted on May 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How to convert html to pdf (something like a generated invoice) and send it to an email
July 16, 2022