ES6+ — Tính năng JavaScript hiện đại

letconst (không dùng var nữa)

let   count = 0;     // có thể gán lại
const MAX   = 100;   // không thể gán lại (const)

// var có vấn đề hoisting & function scope thay vì block scope
// → dùng const mặc định, dùng let khi cần gán lại

Arrow Function

// Cú pháp truyền thống
function add(a, b) { return a + b; }

// Arrow function
const add = (a, b) => a + b;          // trả về ngầm định
const greet = name => `Xin chào ${name}!`;
const log   = () => console.log('hello');

Template Literals

const name = 'Lan';
const age  = 25;

// Thay vì nối chuỗi
console.log('Tên: ' + name + ', tuổi: ' + age);

// Template literal với ${...}
console.log(`Tên: ${name}, tuổi: ${age}`);

// Nhiều dòng
const html = `
  <h1>${name}</h1>
  <p>Tuổi: ${age}</p>
`;

Destructuring

// Array destructuring
const [x, y, z] = [1, 2, 3];
const [first, , third] = [10, 20, 30];  // bỏ qua phần tử

// Object destructuring
const { name, age, city = 'HCM' } = user;  // city có giá trị mặc định

// Trong tham số hàm
function display({ title, author }) {
  console.log(`${title}${author}`);
}

Spread và Rest

// Spread: mở rộng mảng/object
const a = [1, 2, 3];
const b = [...a, 4, 5];          // [1,2,3,4,5]
const merged = { ...obj1, ...obj2 };

// Rest: gom các đối số còn lại
function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4));   // → 10

Array Methods

const products = [
  { name: 'Áo', price: 150000 },
  { name: 'Quần', price: 280000 },
  { name: 'Giày', price: 420000 },
];

// map — biến đổi từng phần tử
const names = products.map(p => p.name);

// filter — lọc phần tử thoả điều kiện
const cheap = products.filter(p => p.price < 300000);

// reduce — tính toán tổng hợp
const total = products.reduce((sum, p) => sum + p.price, 0);

// find — tìm phần tử đầu tiên
const shoes = products.find(p => p.name === 'Giày');

Optional Chaining ?. và Nullish Coalescing ??

const user = null;

// Không báo lỗi khi user là null/undefined
console.log(user?.address?.city);   // → undefined (không crash)

// Giá trị mặc định khi null/undefined (không phải 0 hay '')
const port = config.port ?? 3000;

Async / Await

async function loadData() {
  try {
    const res  = await fetch('https://api.example.com/data');
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('Lỗi:', err);
  }
}

Ví dụ: Các tính năng ES6+

Kết quả
<div id="output" style="font-family:monospace;background:#1e1e1e;color:#d4d4d4;
  padding:1rem;border-radius:6px;line-height:1.8;white-space:pre-wrap"></div>
<button id="runBtn"
  style="margin-top:0.75rem;padding:0.5rem 1.2rem;background:#4472c4;
         color:white;border:none;border-radius:4px;cursor:pointer;font-size:0.95rem">
  ▶ Chạy ví dụ
</button>
document.getElementById('runBtn').addEventListener('click', () => {
  const out = document.getElementById('output');
  const log = [];

  // Template literal
  const name = 'Minh';
  log.push(`Template literal: Xin chào, ${name.toUpperCase()}!`);

  // Destructuring array
  const [r, g, b] = [255, 127, 0];
  log.push(`Destructuring array: r=${r}, g=${g}, b=${b}`);

  // Destructuring object
  const { title, year = 2025 } = { title: 'JavaScript ES6' };
  log.push(`Destructuring object: title="${title}", year=${year}`);

  // Spread
  const arr1 = [1, 2, 3];
  const arr2 = [...arr1, 4, 5];
  log.push(`Spread: [${arr2}]`);

  // Array methods
  const prices = [150, 280, 420, 90, 350];
  const big    = prices.filter(p => p >= 200);
  const total  = prices.reduce((s, p) => s + p, 0);
  log.push(`filter (>=200): [${big}]`);
  log.push(`reduce (tổng): ${total}`);

  // Optional chaining
  const user = { address: null };
  log.push(`Optional chaining: ${user?.address?.city ?? 'Không có thành phố'}`);

  out.textContent = log.join('\n');
});

Bình luận