Life is connecting the dots .

[JS] 2. 제어문(조건문, 반복문) 본문

Programming/JS

[JS] 2. 제어문(조건문, 반복문)

soyeori 2023. 2. 14. 22:55

1. 제어문이란

- 제어(Control flow)란 컴퓨터가 스크립트에서 명령을 실행하는 순서입니다.

- 조건부나 루프와 같이 순차적인 흐름을 변경해야할 때 사용하는 실행문을 제어문이라고 한다.

2. 조건문(Conditional statements)

- 조건에 따라 명령을 수행하도록 하는 제어문이다.

- 단순 반복적인 코드를 더 효율적으로 만들어 주고, 복잡한 조건을 간결하게 만들어 주며, 목적에 맞는 기능을 구현해 준다.

- 조건이 '참'이다라고 여겨지는 것

: false, undefined, null, 0, NaN, ""(empty string)이 아닌 모든 값 그리고 블리언 객체값이 false를 포함하는 객체.

2_1. if / if else / if else if ... else

// Syntax
if (condition) {
  statement1 ;	
  	// condition이 True일 때의 실행문
}

// With an else clause (no 'elseif' keyword in javascript)
if (condition1) {
  statement1 ;	
  	// condition1이 True일 때의 실행문
}
else if (condition2) {
  statement2 ;	
  	// condition2가 True일 때의 실행문
}
else {
  statement3 ;	
  	// condition1, condition2가 False일 때의 실행문
}

2_2. 조건문 활용(토글 만들기)

- night 버튼을 클릭하면 검은 바탕에 흰 글씨인 화면으로,

- day 버튼을 클릭하면 하늘색 바탕에 회색 글씨인 화면을 보여준다.

 

<body>
	<input id="night_day" type="button" value="night" onclick="
    	if (document.querySelector('#night_day').value === 'night') {
    	    document.querySelector('body').style.backgroudColor='black';
            document.querySelector('body').style.color='white';
            document.querySelector('#night_day').value = 'day';
            }
        else {
            document.querySelector('body').style.backgroundColor='powderblue';
            document.querySelector('body').style.color='grey';
            document.querySelector('#night_day').value = 'night';
            }
	">
    <h1>JavaScript</h1>
</body>

2_3. 리팩토링이란?

: 코드의 기능은 유지하되 효율적으로 만드는 것이다. (대표적으로 중복의 제거)

- 위의 코드를 리팩토링을 이용하여 수정하기.

 

// this keyword 와 변수만들기
<body>
	<input id="night_day" type="button" value="night" onclick="
    	var target = document.querySeletor('body');
    	if this.value === 'night') {
    	    target.style.backgroudColor='black';
            target.style.color='white';
            this.value = 'day';
            }
        else {
            target.style.backgroundColor='powderblue';
            target.style.color='grey';
            this.value = 'night';
            }
	">
    <h1>JavaScript</h1>
</body>

3. 반복문(Iteration statements)

- 실행문을 반복하여 수행하도록 하는 제어문이다.

- 같은 코드를 여러번 사용하는 경우에 반복문을 사용하면 코드를 간결하게 만들 수 있고, 유지보수에 용이하다.

3_1. while

while (condition) {
  statement ;
  	// 지정된 조건이 '참'인 동안 반복적으로 수행하는 실행문 (무한 loop 주의!)
}

3_2.  for

// Syntax
for (initialization; condition; afterthought) {
	statement ;	// for반복문 안의 3개 식은 모두 선택사항이다.
 }

 


이 글은 부스트코스[자바스크립트의 시작_생활코딩] 강의 수강 후 개인 공부용으로 작성한 글입니다.

 

참고)

MDN

 

'Programming > JS' 카테고리의 다른 글

스코프(Scope) 란 ?  (0) 2023.06.26
웹 브라우저는 어떻게 화면에 그려질까? Critical Rendering Path  (0) 2023.06.20
[JS] 4. 객체(Objects)  (0) 2023.02.16
[JS] 3. 함수  (0) 2023.02.15
[JS] 1. 자바스크립트의 이해  (0) 2023.02.13