2026년에 더 나은 개발자가 되게 할 15가지 JavaScript 팁
발행: (2026년 3월 29일 AM 06:29 GMT+9)
7 분 소요
원문: Dev.to
Source: Dev.to
이 JavaScript 팁들은 실제로 내 코드 품질을 크게 향상시켰습니다. 불필요한 내용 없이, 바로 적용 가능한 패턴들만 제공합니다.
1. 옵셔널 체이닝은 최고의 친구입니다
// 기존 방식 – 보기 흉하고 오류 발생 가능
const city = user && user.address && user.address.city;
// 현대적인 방식
const city = user?.address?.city;
// 메서드와 함께
const first = arr?.at(0);
const len = str?.trim()?.length;
2. Nullish Coalescing vs OR
// ||는 모든 falsy 값(0, '', false 등)을 사용합니다!
const count = data.count || 10; // BUG: count가 0일 때 10을 반환합니다
// ??는 null/undefined인 경우에만 동작합니다
const count = data.count ?? 10; // CORRECT: count가 0일 때 0을 반환합니다
3. 기본값이 있는 객체 구조 분해
function createUser({
name,
role = 'user',
active = true,
theme = 'light'
} = {}) {
return { name, role, active, theme };
}
// = {} 기본값 덕분에 인자를 전달하지 않아도 호출할 수 있습니다
createUser(); // 정상 작동!
createUser({ name: 'Alice' });
// { name: 'Alice', role: 'user', active: true, theme: 'light' }
4. 배열 메서드와 루프
const users = [
{ name: 'Alice', age: 25, active: true },
{ name: 'Bob', age: 30, active: false },
{ name: 'Charlie', age: 22, active: true }
];
// Get names of active users over 24, sorted alphabetically
const result = users
.filter(u => u.active && u.age > 24)
.map(u => u.name)
.sort();
// Result: ['Alice']
// 결과: [‘Alice’]
5. 병렬 요청을 위한 Promise.allSettled
// Promise.all fails if ANY request fails
// Promise.allSettled waits for all, reports success/failure for each
const results = await Promise.allSettled([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
]);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Request ${index}: success`);
} else {
console.log(`Request ${index}: failed - ${result.reason}`);
}
});
6. WeakMap를 이용한 개인 데이터
const privateData = new WeakMap();
class User {
constructor(name, password) {
privateData.set(this, { password });
this.name = name;
}
checkPassword(input) {
return privateData.get(this).password === input;
}
}
const user = new User('Alice', 'secret123');
console.log(user.checkPassword('secret123')); // true
console.log(user.password); // undefined – truly private!
7. 변환을 위한 Object.fromEntries
const prices = { apple: 1.5, banana: 0.5, cherry: 3.0 };
// 모든 항목에 10 % 할인 적용
const discounted = Object.fromEntries(
Object.entries(prices).map(([key, value]) => [key, value * 0.9])
);
// { apple: 1.35, banana: 0.45, cherry: 2.7 }
8. 논리 할당 연산자
// ||= 은 왼쪽이 falsy일 때만 할당합니다
user.role ||= 'guest';
// &&= 은 왼쪽이 truthy일 때만 할당합니다
user.profile &&= updateProfile(user.profile);
// ??= 은 왼쪽이 null/undefined일 때만 할당합니다
config.timeout ??= 3000;
9. 음수 인덱싱을 위한 Array.at()
const arr = [1, 2, 3, 4, 5];
// Old way
const last = arr[arr.length - 1]; // 5
// Modern way
const last = arr.at(-1); // 5
const secondLast = arr.at(-2); // 4
10. 깊은 복사를 위한 구조화된 복제
// JSON.parse(JSON.stringify()) breaks dates, functions, etc.
const shallow = { ...obj }; // Shallow copy only
// Proper deep clone (Node 17+, all modern browsers)
const deep = structuredClone(obj);
11. 요청 취소를 위한 AbortController
async function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
return response.json();
} catch (err) {
if (err.name === 'AbortError') {
throw new Error('Request timed out');
}
throw err;
}
}
12. 지연 시퀀스를 위한 제너레이터 함수
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
const first10 = Array.from({ length: 10 }, () => fib.next().value);
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
13. 더 나은 디버깅을 위한 오류 원인
async function fetchUser(id) {
try {
const data = await db.query('SELECT * FROM users WHERE id = ?', [id]);
return data;
} catch (err) {
throw new Error(`Failed to fetch user ${id}`, { cause: err });
}
}
// Now you can access the original error
try {
await fetchUser(42);
} catch (err) {
console.log(err.message); // "Failed to fetch user 42"
console.log(err.cause); // Original DB error
}
Source: …
14. Object.groupBy를 사용한 배열 그룹화
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
// ... (rest of the data)
];
// 사용 예시 (최신 JS 엔진 필요):
const grouped = Object.groupBy(inventory, item => item.type);
// {
// vegetables: [{ name: 'asparagus', type: 'vegetables', quantity: 5 }],
// fruit: [{ name: 'bananas', type: 'fruit', quantity: 0 }],
// // …
}
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 1 },
{ name: 'bananas', type: 'fruit', quantity: 5 },
{ name: 'cherries', type: 'fruit', quantity: 2 },
{ name: 'carrots', type: 'vegetables', quantity: 1 },
];
const grouped = Object.groupBy(inventory, ({ type }) => type);
// {
// vegetables: [asparagus, carrots],
// fruit: [bananas, cherries]
// }
15. console 더 효과적으로 사용하기
// Group related logs
console.group('User Authentication');
console.log('Checking credentials...');
console.log('Token validated');
console.groupEnd();
// Time operations
console.time('db-query');
await db.query('...');
console.timeEnd('db-query'); // db-query: 23.4ms
// Table for arrays/objects
console.table(users);
// Assert (throws if false)
console.assert(user.id > 0, 'User ID must be positive');
주요 내용
?.와??를 사용하여 수동 널 검사를 대체하세요.- 모든 결과가 필요할 때는
Promise.allSettled를 선호하세요. - 깊은 복사를 위해
structuredClone을 사용하세요. - 새로운 문법을 받아들이세요 — 모든 최신 브라우저에서 지원됩니다.
이 중 새로 알게 된 것이 있나요? 댓글로 알려주세요!
주간 JavaScript 및 웹‑dev 팁을 원한다면 저를 팔로우하세요.