🔥 10 Mẫu Code Pattern Hiện Đại Trong JavaScript Năm 2025

JavaScript không chỉ là một ngôn ngữ, nó là một hệ sinh thái sống động luôn tiến hóa. Bước sang 2025, để đi trước xu hướng, dev cần nắm những coding pattern hiện đại đang định hình cách viết code.

Dưới đây là 10 pattern hot nhất giúp code ngắn gọn – dễ đọc – ít bug – dễ bảo trì 🚀.

1. Pattern Matching


// Đề xuất (Stage 3 proposal)
match (value) {
  when ({ type: "user", age }) if (age > 18) => "Người dùng hợp lệ",
  when ({ type: "guest" }) => "Khách vãng lai",
  else => "Không xác định"
}

Ưu điểm: rút gọn logic phân nhánh, dễ đọc hơn nhiều.

2. Partial Application & Currying


const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2);

console.log(double(5)); // 10

3. Nullish Coalescing (??) & Optional Chaining (?.)


const user = { profile: null };

console.log(user.profile?.name ?? "Guest"); 
// Guest

4. Immutable Data Patterns


const config = Object.freeze({
  api: "https://api.example.com"
});

config.api = "hack"; // ❌ không thay đổi được

5. Module Federation (Webpack 5)


// webpack.config.js
new ModuleFederationPlugin({
  name: "app1",
  remotes: {
    app2: "app2@http://localhost:3002/remoteEntry.js"
  }
});

6. Async Iteration Pattern


async function* fetchPages() {
  yield await fetch("/page1").then(r => r.json());
  yield await fetch("/page2").then(r => r.json());
}

for await (const page of fetchPages()) {
  console.log(page);
}

7. Proxy-Based Observables


const state = new Proxy({ count: 0 }, {
  set(target, prop, value) {
    console.log(`Thay đổi: ${prop} = ${value}`);
    target[prop] = value;
    return true;
  }
});

state.count = 1; // log: Thay đổi: count = 1

8. Template Literals cho HTML


const name = "Dev";
const html = `
  <div class="card">
    <h2>Hello ${name}</h2>
  </div>
`;
document.body.innerHTML = html;

9. Decorator Pattern (TypeScript)


function Log(target: any, key: string, desc: PropertyDescriptor) {
  const fn = desc.value;
  desc.value = function(...args: any[]) {
    console.log(`Call ${key} with`, args);
    return fn.apply(this, args);
  }
}

class User {
  @Log
  say(msg: string) {
    console.log(msg);
  }
}

new User().say("Hello"); 
// log: Call say with ["Hello"]

10. Type-First Development (TypeScript / JSDoc)


/**
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function sum(a, b) {
  return a + b;
}

🎯 Kết: Áp dụng các pattern trên không chỉ giúp code ngắn gọn – dễ bảo trì, mà còn đưa bạn bắt kịp nhịp phát triển 2025.

👉 Bạn đang dùng pattern nào rồi? Pattern nào bạn muốn thử tiếp theo? Hãy comment chia sẻ nhé 😎.

Categorized in: