Cohe

JavaScript 삼항 연산자 본문

JavaScript, React

JavaScript 삼항 연산자

코헤0121 2024. 6. 17. 13:19
728x90

JavaScript 삼항 연산자

//삼항 연산자 연습

const array = [];  // 상수, 변경되지 않음
// let text = "";  // 재선언이 안됨

// if(array.length === 0) {
//     text = "empty";
// } else {
//     text = "not empty";
//}

let text = array.length === 0 ? "empty" : "not empty";

console.log(text);

// 삼항 연산자 중첩 사용 예시

const condition1 = false;
const condition2 = false;

const value = condition1 ? '와우!!!' : condition2 ? '안녕!!!' : '초';
console.log(value);

에러를 처리하는 방법~

// 자스 문법이 아니지만 알아야 할 개념
function print(person){
    console.log(person === undefined || person === null ?  'no name' : person.name);
}

const person = {
    name: '홍길동'
};

print(person);
print(); // type Error가 뜬다! -> undefined로 뜬다

const person2 = null;
print(person2);

'JavaScript, React' 카테고리의 다른 글

NextJS 기본  (0) 2024.06.25
React - 스타일링  (0) 2024.06.17
React - Hook  (0) 2024.06.17
React - useState  (1) 2024.06.17
리엑트  (0) 2024.06.17