자바스크립트의 if문의 용도와 예제

자바스크립트의 if문은 조건에 따라 다른 코드를 실행하려는 경우에 사용됩니다. 기본 구조는 다음과 같습니다:

if (조건) {
  // 조건이 참일 때 실행되는 코드
}

조건이 true로 평가되면, if문 안의 코드가 실행됩니다. 조건이 false로 평가되면, if문 안의 코드는 건너뜁니다.

아래는 if문을 사용하는 간단한 예제입니다:

let num = 10;

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

위 코드에서 num > 5라는 조건은 true로 평가되므로, “The number is greater than 5″라는 메시지가 콘솔에 출력됩니다.

if문은 else문과 함께 사용하여, 조건이 false일 때 실행될 코드를 추가할 수도 있습니다:

let num = 3;

if (num > 5) {
  console.log('The number is greater than 5');
} else {
  console.log('The number is not greater than 5');
}

위 코드에서 num > 5라는 조건은 false로 평가되므로, “The number is not greater than 5″라는 메시지가 콘솔에 출력됩니다.

또한, else if문을 사용하여 여러 조건을 체크할 수 있습니다:

let num = 3;

if (num > 5) {
  console.log('The number is greater than 5');
} else if (num < 5) {
  console.log('The number is less than 5');
} else {
  console.log('The number is 5');
}

위 코드에서 num > 5라는 조건은 false로 평가되므로, else if문의 조건 num < 5를 확인합니다. 이 조건은 true로 평가되므로, “The number is less than 5″라는 메시지가 콘솔에 출력됩니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다