본문 바로가기
Programming/JavaScript

JavaScript에서 조건문(if, else) 사용하는 방법

by 혀코 2020. 2. 12.

안녕하세요. 혀코입니다.

이번 시간에는 JavaScript에서 조건문(if, else) 사용하는 방법에 대해서 알아보겠습니다.

 

JavaScript에서 조건문(if, else)를 사용하는 방법에는 크게 3가지가 있습니다.

if 만 사용하는 방법, if와 else를 사용하는 방법, if와 else if, else를 사용하는 방법 이렇게 3가지가 있습니다.

 

if 만 사용하는 방법

if (num > 3) {
   console.log('number is greater than three');
}

num에 저장된 숫자가 3보다 큰 경우에만 'number is greater than three'가 출력됩니다.

 

if와 else를 사용하는 방법

if (num > 3) {
   console.log('number is greater than three');
} else {
   console.log('number is less than and equal to three');
}

num에 저장된 숫자가 3보다 큰 경우, 'number is greater than three'가 출력되고, num에 저장된 숫자가 3보다 작거나 같은 경우, 'number is less than and equal to three'가 출력됩니다.

 

if와 else if, else를 사용하는 방법

if (num > 3) {
   console.log('number is greater than three');
} else if (num == 0) {
   console.log('number is equal to zero');
} else {
   console.log('number is less than and equal to three, not zero');
}

num에 저장된 숫자가 3보다 큰경우, 'number is greater than three'가 출력되고, num에 저장된 숫자가 0일 경우, 'number is equal to zero'가 출력되며, num에 저장된 숫자가 0도 아니고 3보다 작거나 같은 수인 경우에 'number is less than and equal to three, not zero'가 출력됩니다.

 

이렇게 JavaScript에서 조건문(if, else) 사용하는 방법에 대해서 알아봤습니다.

유용하셨다면, 공감과 구독 부탁 드립니다.

감사합니다. :)

 

 

 

댓글