9 Tricks To Write Less JavaScript.

0xshoaib

Shoaib Sayyed

Posted on May 7, 2020

9 Tricks To Write Less JavaScript.

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";
Enter fullscreen mode Exit fullscreen mode

2. Assignment Operator

//Longhand
x = x + y;
x = x - y;

//Shorthand
x += y;
x -= y;
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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}!`;
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

7. Object Array Notation

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

//Shorthand
let arr = ["html", "css", "js"];
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
0xshoaib
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