Java Script #조건문 (if/switch)

달다로·2024년 6월 2일
0

JS

목록 보기
5/26
post-thumbnail

📌Java Script #조건문


if statement

if else if else
조건의 결과 (truthy, falsy) 에 따라 다른 코드를 실행하는 구문
if 문을 사용해서 어떤 일이 일어났을 때 그 다음에 무슨 일을 할지 결정할 때 사용된다.

  • 조건이 1개 일 때 : if
  • 조건이 2개 일 때 : if + else
  • 조건이 2개 이상일때 : if + else if ... + else

if

// 변수 선언
let isShow = true;
let checked = false;

if (isShow) {
	console.log('Show!'); // 결과가 true 라서 Show! 라고 실행됨
}

if (checked) {
	console.log('Checked!') // 결과가 false 라서 결과가 실행되지 않음
}

else

// 변수 선언
let isShow = true;

if (isShow) {
	console.log('Show!'); // true 라서 show! 가 출력됨, 만약에 isShow = false 로 표기했을 경우 Hide?가 실행됨
} else {
	console.log('Hide?';
}

if else

if (a === 0) {
    console.log('a is 0')
} else if (a === 2) {
    console.log ('a is 2')
} else {
    console.log ('rest...') // 그 외 나머지 값
}

switch statement

//랜덤값 부여
function random() {
    return Math.floor(Math.random() * 10)
}
//switch문
switch (a) {
  case 0:
    console.log('a is 0');
    break
  case 2:
    console.log ('a is 2');
    break
  default:
    console.log ('rest...') // 그 외 나머지 값
}

🔥 if 문과 switch 문 의 차이점

  • switch 문
    여러가지 특정 값 중 하나를 선택할 때 좋다. (예를 들면 번호로 지정되어있는 경우)
int 과일번호 = 2;

switch(과일번호) {
    case 1:
        cout << "사과";
        break;
    case 2:
        cout << "바나나";
        break;
    case 3:
        cout << "딸기";
        break;
    default:
        cout << "알 수 없는 과일";
}
  • if 문
    다양한(복잡한) 조건이 있을 때 사용할 때 좋다.
    밑의 예시로 보면, 사과가 1번 빨간색 인 경우에는 true 지만 사과가 1번 초록색 일 경우에는 false 값이 나온다.
int 과일번호 = 2;
bool isRed = true;

if (과일번호 == 1 && isRed) {
    cout << "빨간 사과를 골랐어";
} else if (과일번호 == 2) {
    cout << "바나나를 골랐어";
} else if (과일번호 == 3) {
    cout << "딸기를 골랐어";
} else {
    cout << "알 수 없는 과일이야";
}
profile
나이들어서 공부함

0개의 댓글