여러분이 사용하고 계신 브라우저는 HTML5를 지원하지 않기 때문에 몇몇 요소가 제대로 보이도록 JScript를 사용하고 있습니다. 하지만 여러분의 브라우저 설정에서 스크립트 기능이 꺼져있으므로, 현재 페이지를 제대로 확인하시려면 스크립트 기능을 켜주셔야 합니다. Javascript - 기초 - 조건문
Javascript – 기초 – 조건문
2년전 작성
2년전 수정

조건문을 입력하여 특정 조건에서만 코드가 실행되고자 할 때 이용할 수 있다.

조건문

프로그래밍 언어를 코딩할 때 조건을 입력하고 조건에 부합하면 작업을 수행하도록 할 수 있다.

조건문에는 if, else if, else와 switch, 조건 연산자를 사용할 수 있다.

if, else if, else

가장 기본이 되는 조건문이다.

Javascript
if (조건식) {
...
}
else if (조건식) {
...
}
else {
...
}

이런식으로 입력을 한다.

조건문
if
:
조건식을 입력할 때 가장 기초가되는 조건문이다.
else if
:
if에 해당하지 않는 조건인데 하나가 아니라 조건을 따로따로 실행해야할 때 사용한다.
else
:
if나 else if에 해당하지 않는 조건식이 나오면 이 조건문으로 실행된다.

조건식

이 때 조건식에는 비교연산자와 논리연산자를 사용한다.

비교 연산자
===
:
a === b와 같이 사용하며 값이 같은지 확인하고 같으면 true로 반환한다. a === true는 줄여서 a로 입력할 수 있다.
!==
:
a !== b와 같이 사용하며 값이 다른지 확인하고 다르면 true로 반환한다.
<
:
a < b와 같이 사용하며 왼쪽 값이 오른쪽 값보다 작은지 확인하고 작다면 true로 반환한다.
>
:
a > b와 같이 사용하며 왼쪽 값이 오른쪽 값보다 큰지 확인하고 크다면 true로 반환한다.
<=
:
a <= b와 같이 사용하며 왼쪽 값이 오른쪽 값보다 작거나 같은지 확인하고 작거나 같다면 true로 반환한다.
>=
:
a >= b와 같이 사용하며 왼쪽 값이 오른쪽 값보다 크거나 같은지 확인하고 크거나 같다면 true로 반환한다.
논리 연산자
&&
:
AND. 전체 조건식이 true를 반환하기 위해 조건식 사이에 &&를 기재해놓은 조건식들의 값이 모두 true로 반환하는지 조건식을 확인하고 2개 이상의 조건식을 연결할 수 있게 한다.
||
:
OR. 전체 조건식이 true를 반환하기 위해 조건식 사이에 ||를 기재해놓은 조건식들이 개별적으로 true로 반환하는지 조건식을 확인하고 2개 이상의 조건식을 연결할 수 있게 한다.
HTML
Javascript
const select = document.querySelector('select');
const para = document.querySelector('p');

select.addEventListener('change', setWeather);

function setWeather() {
const choice = select.value;

if (choice === 'sunny') {
para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
}
else if (choice === 'rainy') {
para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
}
else if (choice === 'snowing') {
para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
}
else if (choice === 'overcast') {
para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
}
else {
para.textContent = '';
}
}
기본 예시

 

사용된 코드 설명
const select = document.querySelector(‘select’);
:
select 라는 함수를 선언하고 html 문서의 select 요소에 접근한다. 여기서 select가 아닌 class 이름이나 ID와 같이 선택자 이름으로 입력해도 된다.
const para = document.querySelector(‘p’);
:
para 라는 함수를 선언하고 html 문서의 p 요소에 접근한다. 여기서 p가 아닌 class 이름이나 ID와 같이 선택자 이름으로 입력해도 된다.
select.addEventListener(‘change’, setWeather);
:
변수 select 값이 변경되면 setWeather() 함수에 전달하는 이벤트를 등록한다.
function setWeather() { … }
:
setWeather() 함수를 선언한다.
const choice = select.value;
:
choise 라는 함수를 선언하고 select의 값을 가져온다.
para.textContent = ‘ … ‘;
:
변수 para에 글자 …을 추가한다.

switch

간단하게 조건문을 입력할 수 있다. 복수의 if 문은 switch로 바꿀 수 있다.

Javascript
switch(값 불러올 변수) {
case 조건값: //if (값 불러올 변수 === 조건값)과 동일함.
...
break;

case 조건값2: //if (값 불러올 변수 === 조건값2)과 동일함.
...
break;

default:
...
}

이런식으로 입력을 한다.

조건문
switch(값 불러올 변수)
:
switch 문을 선언한다. 값 불러올 변수 이름을 입력하여 일치하는지 확인하는 조건문이다.
case
:
각 case에는 break;를 넣어줘야 다음 코드를 실행한다. case는 하나의 switch문 안에 원하는만큼 추가할 수 있다.
default
:
else와 동일하게 사용하면 된다. 필수가 아니므로 꼭 넣지 않아도된다.
HTML
Javascript
const select = document.querySelector('select');
const para = document.querySelector('p');

select.addEventListener('change', setWeather);

function setWeather() {
const choice = select.value;

switch (choice) {
case 'sunny':
para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
break;
case 'rainy':
para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
break;
case 'snowing':
para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
break;
case 'overcast':
para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
break;
default:
para.textContent = '';
  }
}
기본 예시

 

위와 같으나 조건문 부분만 차이가 있다.

조건 연산자

조건식이 true / false만 반환한다면 if / else보다 더 간결하게 표현할 수 있다.

(조건식/값) ? 변경할 코드 : 기존 코드

이런식으로 입력을 한다.

HTML
<label for="theme">Select theme: </label>
<select id="theme">
<option value="white">White</option>
<option value="black">Black</option>
</select>

<h1>This is my website</h1>
Javascript
const select = document.querySelector('select');
const html = document.querySelector('html');
document.body.style.padding = '10px';

function update(bgColor, textColor) {
html.style.backgroundColor = bgColor;
html.style.color = textColor;
}

select.onchange = function() {
( select.value === 'black' ) ? update('black','white') : update('white','black');
}
기본 예시

 

사용된 코드 설명
const html = document.querySelector(‘html’);
:
html 라는 함수를 선언하고 html 요소에 접근한다.
document.body.style.padding = ’10px’;
:
html 문서의 body에 style=”padding: 10px;”과 같은 인라인 CSS를 추가한다.
function update(bgColor, textColor) { … }
:
update 함수를 선언하고 bgColor, textColor 인자를 만든다.
( select.value === ‘black’ ) ? update(‘black’,’white’) : update(‘white’,’black’);
:
변수 select의 값이 ‘black’이면 bgColor:white, textColor:black 대신에 bgColor:black, textcolor:white로 변경한다.
참고
관련 포스트
Javascript - 기초 - 조건문 - 현재글

Mingg`s Diary
밍구
공부 목적 블로그