[Javascript] 제어 흐름
JS control flow, if switch loop, JS 반복문
정의
JS 의 제어 흐름 구문. 분기, 반복, 종료 / 계속.
if / else
if (cond) { ... }
else if (cond2) { ... }
else { ... }
// 단일 표현식이면 ternary 권장
const x = cond ? a : b;
switch
switch (x) {
case 1:
// fall-through 주의
break;
case 2:
case 3:
// 2 or 3
break;
default:
// ...
}
break 없으면 다음 case 로 fall-through. ES2023+ Map lookup 이 더 명시적.
// switch 대안
const action = {
create: () => create(),
update: () => update(),
delete: () => del(),
}[type];
action?.();
for
for (let i = 0; i < n; i++) { ... }
// 무한 + break
for (;;) {
if (cond) break;
}
for…of (iterable)
for (const x of arr) { ... }
for (const [k, v] of map) { ... }
for (const ch of 'hello') { ... }
break, continue 지원. index 가 필요하면 arr.entries() 또는 일반 for.
for (const [i, v] of arr.entries()) { ... }
for…in (객체 키)
for (const key in obj) { ... }
CAUTION
for...in 은 prototype chain 의 키도 포함. 배열에 쓰지 말 것 (의도와 다른 순서). 객체에는 Object.keys/entries 가 더 안전.
while / do-while
while (cond) { ... }
do {
// 최소 1 회 실행
} while (cond);
break / continue
for (...) {
if (skip) continue;
if (stop) break;
}
// label 로 nested loop 제어
outer: for (...) {
inner: for (...) {
if (cond) break outer;
if (cond2) continue outer;
}
}
label 은 가독성 떨어져 보통 회피, 함수로 추출이 더 깔끔.
ternary
const x = cond ? a : b;
const tag = age >= 18 ? 'adult' : age >= 13 ? 'teen' : 'child'; // chained
logical operators 의 short-circuit
a && b // a 가 truthy 면 b 평가
a || b // a 가 truthy 면 a
a ?? b // a 가 nullish 면 b
conditional execution
isLoggedIn && showProfile();
config.debug && console.log(...);
// 옛 if 패턴
if (isLoggedIn) showProfile();
if 가 더 명시적, lint 도구 (no-unused-expressions) 가 short-circuit 패턴 경고할 수 있음.
return early (가독성)
// ❌ 중첩
function process(user) {
if (user) {
if (user.active) {
if (user.verified) {
return doWork(user);
}
}
}
return null;
}
// ✓ early return
function process(user) {
if (!user) return null;
if (!user.active) return null;
if (!user.verified) return null;
return doWork(user);
}
자주 만나는 패턴
Array methods 가 for 보다 깔끔
// for
const result = [];
for (const x of arr) {
if (x > 0) result.push(x * 2);
}
// 함수형
const result = arr.filter(x => x > 0).map(x => x * 2);
조건부 객체 빌딩
const obj = {
a: 1,
...(cond && { b: 2 }),
...(other && { c: 3 }),
};
모드별 분기
const handlers = {
pending: handlePending,
success: handleSuccess,
error: handleError,
};
handlers[state]?.(payload);
함정
1. ==/!= 의 강제 변환
if (x == 0) { ... } // '' 0 false null 등 모두 match
if (x === 0) { ... } // 정확
2. switch 의 fallthrough
switch (x) {
case 1:
doOne();
// break 빠뜨림 → 다음 case 실행
case 2:
doTwo();
}
의도라면 주석 // fallthrough 명시.
3. for-in 의 prototype 키
Array.prototype.custom = function() {};
for (const k in [1, 2, 3]) console.log(k);
// '0', '1', '2', 'custom' ⚠️
for...of 또는 for (let i = 0; ...) 권장.
4. 빈 catch
try { ... } catch {} // ⚠️ 에러 무시 위험
참고
이 글의 용어 (3개)
- [Javascript] Arrayjavascript
- 정의 JavaScript 의 는 순서 있는 객체. 정수 키 + . 풍부한 메서드 (map/filter/reduce/...) 가 함수형 스타일을 지원. 생성 핵심 메서드 (반복) …
- [Javascript] Error / try-catchjavascript
- 정의 JS 의 에러 처리. 로 던지고 로 잡는다. 내장 Error 타입과 사용자 정의 Error. throw / try / catch 는 에러 유무와 무관하게 실행. 내장 Err…
- [Javascript] Iterator / Generatorjavascript
- 정의 - Iterator protocol : 메서드가 반환 - Iterable protocol : 가 iterator 반환 - Generator : 으로 정의, yield 로 값…
💬 댓글