
자바스크립트는 동적 타입 언어로, 상황에 따라 자동으로 형변환이 일어난다. 이를 이해하고 활용하면 더 간결한 코드를 작성할 수 있다.
// 😕 불필요하게 긴 조건문
if ('string'.length > 0) {}
if (!isNaN(10)) {}
위 코드들은 명시적인 비교를 하고 있지만, 사실 불필요한 과정을 거치고 있다
조건문에서 자동으로 boolean으로 형변환 하기 때문
// 👍 더 간결한 조건문
if ('string'.length) {} // 0이 아닌 숫자는 truthy
if (10) {} // 0이 아닌 숫자는 truthy
단축평가는 논리 연산자를 사용해 코드를 더 간결하게 만든다
function favoriteDog(someDog){
let favoriteDog;
if(someDog){
favoriteDog = dog;
}else{
favoriteDog = '냐옹';
}
return favoriteDog + '입니다';
}
문제점
// 👍 단축평가 활용
function favoriteDog(someDog){
return (someDog || '냐옹') + '입니다'
}
개선점
// 😱 복잡한 중첩 조건문
const getActiveUserName(user, isLogin){
if (isLogin){
if (user) {
if (user.name){
return user.name
} else {
return '이름없음'
}
}
}
}
문제점
// 👍 단축평가로 개선된 버전
const getActiveUserName(user, isLogin){
if (isLogin && user){
return user.name || '이름없음'
}
}
개선점