# switch , 삼항연산자

## Switch

이번엔 switch 문법 배워봅시다.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
</head>
<body>

<div id="quiz">
  <h4>물에 빠지면 누구먼저 구할 것임?</h4>
  <button>친구</button>
  <button>부모님</button>
  <button>반려동물</button>
</div>

  <script>
  
    
  </script>

</body>
</html>
```

이렇게 html 코드를 짜고 button을 클릭 했을때 각 버튼별로 아니면 quiz div에 이벤트 리스너를 넣고

선택한 버튼 별로 조건문을 작성해서 할 수 도있겠지만

switch/case 문법을 써서 한번 사용해봅시다.

Switch/case 예시

```javascript
let 변수 = 7 + 2;

switch(변수) {
   case 3 :
     alert("변수 3임");
     break
   case 4 :
     alert("변수 4임");
     break
   default :
     alert("아무것도 해당안됨");
     break
}


//차이점
// if는 다양한 조건식 가능
// switch는 변수 1개만 테스트 가능



$("#quiz").on('click', function (e){
    switch (e.target.innerHTML){
      case '친구' :
        alert('인싸네요');
        break;
      case '부모님' :
        alert('효자네요');
        break;
      case '반려동물' :
        alert('동물애호가네요');
        break;
    }

});

```

## 삼항연산자

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

조건문이 참이면 : 앞이 실행, 거짓이면 : 뒤가 실행된다.

if else문의 대체제로 자주 사용된다.

```javascript
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"

```

삼항연산자를 너무 남용하면 아래와 같은 대참사가 나온다.

짠사람 말고는 한참을 해석해야 알아볼 수 있다.

이런 코드는 좋은 코드가 아니다.

<figure><img src="/files/NChppbnuiOnzAwtKt43X" alt=""><figcaption><p>삼항연산자의 나쁜 예</p></figcaption></figure>

나중에 실력을 좀 쌓고나면 꼭 이영상을 보면서 내가 짠 코드를 한번 리뷰 해보시길!!

{% embed url="<https://youtu.be/S6eMI_lDn9o?si=JlkRju7cj64bEJTR>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/javascript/switch.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
