javascript

[javascript] 03. 조건문_ if문, switch문

쿨키드 2022. 8. 26. 16:44
조건문(conditional statements)
조건문이란 프로그램 내에서 주어진 표현식의 결과에 따라 별도의 명령을 수행하도록 제어하는 실행문
조건문 중에서 가장 기본이 되는 실행문은 if 문

자바스크립트에서 사용할 수 있는 조건문의 형태는
1. if 문
2. if / else 문
3. if / else if / else 문
4. switch 문

if 문

if 문은 표현식의 결과가 참(true)이면 주어진 실행문을 실행하며, 거짓(false)이면 아무것도 실행하지 않는다.


if (표현식) {
표현식의 결과가 참일 때 실행하고자 하는 실행문;
}

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2022.07.13. 조건문 01_IF문 01</title>
</head>

<body>
    <div id="txt"></div>
    <script>

        let age = 20;
        // if 만약에 ()이 참으로 판별되면 {}을 실행하라.

        if (age > 9) {
            console.log(`나는 ${age} 살 잼파티`)
        }
        // ↗와 같은 말임.
        //논리연산자를 사용한 조건부 실행
        age > 9 && console.log('키드키듴');


        if (age > 9) {
            console.log('키드키듴')
        } else {
            console.log('아득아득')
        }
        // ↗와 같은 말임.
        // 삼항연산자를 이용한 조건부 실행. 삼항 연산자는 else가 필수임
        age > 9 ? console.log('키드키듴') : console.log('아득아득');


        txt.innerText = `나는 ${age} 살 잼파티`;

    </script>
</body>

</html>
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2022.07.13. 조건문 02_if문 02</title>
</head>

<body>
    <div id="txt"></div>
    <input id="input">
    <button id="btn">click</button>
    <script>

        btn.addEventListener('click', function () {
            console.log('check', input.value);
            let age = input.value;


            if (age < 10) {
                txt.innerText = '안돼 돌아가'
            } else if (age >= 10 && age <= 20) {
                txt.innerText = '된다'
            } else if (age > 20 && age <= 40) {
                txt.innerText = 'w0w'
            } else {
                txt.innerText = 'ㅇㅅaㅇ'
            }
        })
    </script>
</body>

</html>
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2022.07.13. 조건문 03_if문 03</title>
</head>

<body>

    <script>

        let 성적 = 70;

        if (성적 >= 60) {
            if (성적 > 80) {
                console.log('와우');
            } else {
                console.log('합격');
            }
        } else {
            console.log('불합격');
        }
    </script>
</body>

</html>


switch 문
switch 문은 if / else 문과 마찬가지로 주어진 조건 값에 따라 프로그램이 다른 명령을 수행하도록 하는 조건문
이러한 switch 문은 if / else 문보다 가독성 측면에서 더 좋음.

switch (조건 값) {
case 값1:
조건 값이 값1일 때 실행하고자 하는 실행문;
break;
case 값2:
조건 값이 값2일 때 실행하고자 하는 실행문;
break;
...
default:
조건 값이 어떠한 case 절에도 해당하지 않을 때 실행하고자 하는 실행문;
break;
}

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2022.07.13. 조건문 04_switch 01</title>
</head>

<body>
    <script>
        let age = '';

        switch (age) {
            case '아들': console.log('그래 아들');
                break;
            case '아부지': console.log('그려 아부지');
                break;
            default: console.log('귀신');
        }
    </script>
</body>

</html>


else 문

if 문과 같이 사용할 수 있는 else 문은 if 문의 표현식 결과가 거짓(false)일 때 주어진 실행문을 실행

else if 문

else if 문은 if 문처럼 표현식을 설정할 수 있으므로, 중첩된 if 문을 좀 더 간결하게 표현 가능

하나의 조건문 안에서 if 문과 else 문은 단 한 번만 사용될 수 있다.

하지만 else if 문은 여러 번 사용되어 다양한 조건을 설정할 수 있습다.


👉 else문
if (표현식) {
표현식의 결과가 참일 때 실행하고자 하는 실행문;
} else {
표현식의 결과가 거짓일 때 실행하고자 하는 실행문;
}


👉 else if문
if (표현식1) {
표현식1의 결과가 참일 때 실행하고자 하는 실행문;
} else if (표현식2) {
표현식2의 결과가 참일 때 실행하고자 하는 실행문;
} else {
표현식1의 결과도 거짓이고, 표현식2의 결과도 거짓일 때 실행하고자 하는 실행문;
}

👉 삼항 연산자에 의한 조건문
문법)
표현식 ? 반환값1 : 반환값2