삼항 연산자는 “?” 와 “:”를 이용한 조건부 연산자로 if문과 비슷한 동작을 합니다.

(expr1) ? (expr2) : (expr3)

expr1이 참이면 expr2를 반환하고, 거짓이면 expr3을 반환합니다.

<script>
 var a = null ? 'null' : "var";
 document.write(a);
 // 출력: var


 // 위 예제는 다음의 if/else 구문과 동일합니다
 var b;
 if (null) {
   b = 'null';
 } else {
   b = "var";
 }
 document.write(b);
 // 출력 var
</script>

<script>
  document.write(true ? 'true' : false ? 't': 'f');
  // true

  document.write((true ? 'true' : 'false') ? 't' : 'f');
  // t
</script>

<script>
  document.write( 0 ? '' : 0 ? '' : 0 ? '' : 3); // 출력: 3
</script>

0 댓글