10 Tips JavaScript Modern yang Wajib Kamu Ketahui
Kumpulan tips dan trik JavaScript modern yang akan meningkatkan produktivitas dan kualitas kode kamu. Dari optional chaining hingga structured clone.
Pendahuluan
JavaScript terus berkembang dengan fitur-fitur baru yang powerful. Berikut 10 tips yang akan membuat kode kamu lebih bersih dan efisien.
1. Optional Chaining (?.)
Akses properti nested tanpa takut error:
const userName = user?.profile?.name ?? 'Anonymous';
const firstHobby = user?.hobbies?.[0];
const result = user?.getFullName?.();
2. Nullish Coalescing (??)
Lebih presisi dibanding || karena hanya mengecek null dan undefined:
const count = 0;
console.log(count || 10); // 10 (bukan yang diinginkan!)
console.log(count ?? 10); // 0 (benar!)
3. Structured Clone
Copy deep object dengan mudah:
const original = { name: 'Wawan', data: { scores: [1, 2, 3] } };
const clone = structuredClone(original);
clone.data.scores.push(4);
console.log(original.data.scores); // [1, 2, 3] — tidak terpengaruh!
4. Array.at()
Akses elemen array dari belakang:
const arr = ['a', 'b', 'c', 'd'];
console.log(arr.at(-1)); // 'd'
console.log(arr.at(-2)); // 'c'
5. Object.groupBy()
Grouping array dengan mudah:
const items = [
{ name: 'Apel', type: 'buah' },
{ name: 'Wortel', type: 'sayur' },
{ name: 'Jeruk', type: 'buah' },
];
const grouped = Object.groupBy(items, ({ type }) => type);
// { buah: [...], sayur: [...] }
6. Promise.allSettled()
Handle multiple promises tanpa short-circuit:
const results = await Promise.allSettled([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments'),
]);
const successful = results.filter(r => r.status === 'fulfilled');
const failed = results.filter(r => r.status === 'rejected');
7. Top-level Await
Gunakan await di top-level module:
// config.js
const response = await fetch('/api/config');
export const config = await response.json();
8. String replaceAll()
Replace semua occurrence tanpa regex:
const text = 'foo-bar-baz';
console.log(text.replaceAll('-', '_')); // 'foo_bar_baz'
9. Logical Assignment Operators
Gabungan operator logika dan assignment:
// Sebelum
user.name = user.name || 'Anonymous';
// Sesudah
user.name ||= 'Anonymous';
// Nullish assignment
user.settings ??= {};
10. Using Declaration (TC39 Stage 3)
Resource management otomatis:
{
using file = await openFile('data.txt');
const content = await file.read();
// file otomatis ditutup di akhir block
}
Kesimpulan
Dengan menguasai fitur-fitur modern JavaScript ini, kode kamu akan jadi lebih bersih, aman, dan efisien. Pastikan target browser mendukung fitur yang kamu gunakan, atau gunakan transpiler seperti Babel atau TypeScript.
Happy coding! ✨