JavaScript - 삼항연산자 사용방법

신혜린·2023년 1월 29일
0

wecode42

목록 보기
17/32

삼항연산자

삼항연산자는 세 개의 피연산자를 받는 유일한 연산자를 의미한다.

  • 조건문?
  • 조건문이 truty(참)일 경우 실행할 표현식 :
  • 조건문이 falsy(거짓)일 경우 실행할 표현식

-> 위와 같은 순서로 배치됨.

function getFee(isMember) {
  return (isMember ? '$2.00' : '$10.00');
}

console.log(getFee(true));
// Expected output: "$2.00"

console.log(getFee(false));
// Expected output: "$10.00"

console.log(getFee(null));
// Expected output: "$10.00"

false 이외의 falsy한 표현식에는 null, NaN, 0, 비어있는 문자열(""), 그리고 undefined가 있다.


연결된 조건문 처리

조건 연산자는 if...else문의 대체재로 빈번히 사용되는데, 연결된 if ...else if ...else if ...else와 같이 연결문으로 쓰이기도 한다.

function example(...) {
  return condition1 ? value1 // = if (condition1) {return value1;}
  		:condition2 ? value2 // = if (condition2) {return value2;}
  		:condition3 ? value3 // = if (condition3) {return value3;}
  		:value4; // = else {return value4;}
}
profile
개 발자국 🐾

3개의 댓글

comment-user-thumbnail
2023년 2월 6일

ismember 메소드? 함수에서 0또는 1을 리턴하게 되나요???

1개의 답글