9 mẹo rút ngắn code JavaScript siêu ngầu 😎

07 tháng 05, 2020 - 1177 lượt xem

Bắt đầu luôn nhé!

1. Khai báo biến

//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. Viết vòng lặp ngắn gọn

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 với Key và Value giống hệt nhau

//Longhand
const userDetails = {
  name: name, // 'name' key = 'name' variable
  email: email,
  age: age,
  location: location,
};

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

Bài viết được dịch tại đây.

Bình luận

avatar
Hoàng Văn Cương 2020-05-07 09:15:59.48848 +0000 UTC
Wao...không hiểu gì cả vì chưa học mà. Haha. Nhưng thấy bảo khai báo biến trong Js có vấn đề vì không có kiểu. =)
Avatar
* Vui lòng trước khi bình luận.
Ảnh đại diện
  +154 Thích
+154