본문 바로가기
Programming Languages/JavaScript

[JavaScript] 조건문

by 더 이프 2023. 10. 13.
728x90

목차

    🌈 JavaScript에서 조건문 사용하기: 분기의 세계로 여행하자! 🌟

    안녕하세요, JavaScript 여행자 여러분! 🎒 오늘은 프로그래밍 세계의 가장 기본적이면서도 중요한 주제 중 하나인 조건문에 대해 함께 탐험해보려고 합니다. 조건문은 프로그램의 흐름을 제어하는 데 필수적인 요소입니다. 그럼 지금부터 조건문의 신비로운 세계로 떠나볼까요?

     

    1. 🌳 if 문

    if 문은 가장 기본적인 조건문으로, 주어진 조건이 참인 경우에만 코드 블록을 실행합니다.

    let age = 16;
    
    if (age >= 18) {
        console.log("당신은 성인입니다.");
    }

    위의 코드에서 age >= 18이라는 조건은 거짓이므로, console.log는 실행되지 않습니다.

     

    2. 🍂 if-else 문

    조건이 참인 경우와 거짓인 경우로 분기하여 서로 다른 코드를 실행하려면 if-else 문을 사용합니다.

    if (age >= 18) {
        console.log("당신은 성인입니다.");
    } else {
        console.log("당신은 미성년자입니다.");
    }

     

    3. 🍁 if-else if-else 문

    두 개 이상의 조건을 검사하려면 if-else if-else 구조를 사용합니다.

    let score = 85;
    
    if (score >= 90) {
        console.log("A등급");
    } else if (score >= 80) {
        console.log("B등급");
    } else if (score >= 70) {
        console.log("C등급");
    } else {
        console.log("D등급");
    }

     

    4. 🌈 switch 문

    여러 개의 값 중에서 하나를 선택하여 분기를 수행하려면 switch 문을 사용합니다.

    let fruit = '사과';
    
    switch(fruit) {
        case '바나나':
            console.log("노랗게 익었군요!");
            break;
        case '사과':
            console.log("달콤한 사과!");
            break;
        default:
            console.log("어떤 과일인지 모르겠어요.");
    }

    📌 주의: 각 case 뒤에 break;를 넣어야 해당 조건 이후의 코드가 실행되지 않습니다.

     

    🚀 마치며...

    JavaScript에서 조건문은 코드의 흐름을 제어하는 중요한 도구입니다. 조건문을 사용하여 다양한 상황에 대응하는 스마트한 프로그램을 작성해보세요!


    Reference:

     

    Conditional (ternary) operator - JavaScript | MDN

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execu

    developer.mozilla.org

     

    if...else - JavaScript | MDN

    The if...else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.

    developer.mozilla.org

     

    switch - JavaScript | MDN

    The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switc

    developer.mozilla.org


    💻 Happy Coding! 💻