Javascript Tips - Code This, Not That

Sau đây là một vài tip khi viết JS sao cho code của mình được mượt mà và hiệu quả nhất 🌿
1.Console log
const nam = {name: 'Nam', age: '24', gender: 'Male'};
const vu = {name: 'Vu', age: '26', gender: 'Female'};
const van = {name: 'Van', age: '24', gender: 'Female'};
'Bad Code 💩'
console.log(nam);
console.log(vu);
console.log(van);
'Good Code ✅'

▪️Computed property names

console.log('%c My Friends', 'color: blue;');
console.log({nam, vu, van});

▪️Console.table(...)

console.log('%c My Friends', 'color: blue;');
console.table([nam, vu, van]);

kết quả trả về, ta nhận được:

▪️Console.time

console.time('looper');

let i = 0;
while(i < 100000){i++};

console.timeEnd('looper');

▪️Stack Trace Logs

const deleteMe = () => console.trace('bye bye ^^');

deleteMe();
2.Destructuring
const dog = {
  name: 'Vi',
  type: 'Husky',
  legs: 4,
  weight: 15
}
'Bad Code 💩'
function information(animal){
  return `Ten toi la ${animal.name}, toi nang ${animal.weight}, toi thuoc giong ${animal.type}`;
}
'Good Code ✅'
function information({name, weight, type}){
  return `Ten toi la ${name}, toi nang ${weight}, toi thuoc giong ${type}`;
}

// OR

function information(animal){
  const {name, weight, type} = animal;
  return `Ten toi la ${name}, toi nang ${weight}, toi thuoc giong ${type}`;
}
3.Template literals
const cat = {
  name: 'Vu',
  type: 'Cat',
  legs: 4,
  weight: 3,
  skills: ['chay', 'nhay'],
  age: 3
}
'Bad String Code 💩'
let infor = ' Xin chao! Toi la ' + cat.name + ', toi thuoc loai ' + cat.type + ', toi nang ' +
    cat.weight + ' kg, toi co the ' + cat.skills.join(' va ');
'Good String Code ✅'
 const {name, type, weight, skills} = cat;
 
 infor = `Xin chao! Toi la ${name}, toi thuoc loai ${type}, toi nang ${weight} kg, 
     toi co the ${skills.join(' va ')}`;

 console.log(infor);

▪️Advanced Example

function catAge(str, age){
  const ageStr = age > 5 ? 'old' : 'young';
  return `${str[0]}${ageStr} at ${age} years`;
}

const infor2 = catAge`This cat is ${cat.age}`;
4.Spread syntax

▪️Object

const pikachu = {name: 'Pikachu'};
const stats = {hp: 80, attack: 100, defense: 50};
'Bad Object Code 💩'
pikachu['hp'] = stats.hp;
pikachu['attack'] = stats.attack;
pikachu['defense'] = stats.defense;

// OR

const lv5 = Object.assign(pikachu, stats);
const lv10 = Object.assign(pikachu, {hp: 100});
'Good Object Code ✅'
const lv5 = {...pikachu, ...stats};
const lv10 = {...pikachu, hp: 100};

▪️Arrays

let pokemon = ['Pikachu', 'Meow', 'Charizard'];
'Bad Array Code 💩'
pokemon.push('Blastoise');
pokemon.push('Venusaur');
pokemon.push('Raichu');
'Good Array Code ✅'
// Push
pokemon = [...pokemon, 'Blastoise', 'Venusaur', 'Raichu'];

// UnShift

pokemon = ['Blastoise', 'Venusaur', 'Raichu', ...pokemon];
5.Loops
const orders = [100, 30, 200, 15, 86];
'Bad Loop Code 💩'
const total = 0;
const withTax = [];
const highValue = [];
for (i = 0, i < orders.length; i++){
  // Reduce
  total += orders[i];
  
  // Map
  withTax.push(orders[i] * 1.2);
  
  // Filter
  if (orders[i] > 100) {
    highValue.push(orders[i]);
  }
}
'Good Loop Code ✅'
// Reduce
const total = orders.reduce((acc, cur) => acc + cur)

// Map
const withTax = orders.map(v => v * 1.2);

// Filter
const highValue = orders.filter(v => v > 100);
6.Async / Await
const random = () => {
  return Promise.resolve(Math.random())
}
'Bad Promise Code 💩'
const sumRandomAsyncNums = () => {
  let first;
  let second;
  let third;
 
 return random()
     .then(v => {
         first = v;
         return random();
     })
     .then(v => {
         second = v;
         return random();
     })
     .then(v => {
         third = v;
         return first + second + third;
     })
     .then(v => {
         console.log(`Result ${v}`);
     })
}
'Good Loop Code ✅'
const sumRandomAsyncNums = async() => {
  const first = await random();
  const second = await random();
  const third = await random();
  
  console.log(`Result ${first + second + third}`);
}

Cảm ơn các bạn đã đọc bài viết của mình 😍