조건문 (if문)
조건문은 말 그대로 조건에 따라 실행된다.
기본구문은 if (조건문) {실행문} 이 된다.
조건문이 사실(true)라면 실행문의 코드가 실행되고 그렇지 않으면 실행되지 않는다.
const a = 20;
const b = 30;
if (a < b) {
console.log("a");
}; // a
const a = 20;
const b = 30;
if (a > b) {
console.log("a");
} else {
console.log("b");
} // b
조건문이 true가 아닐 때 실행되게 하는 else도 있다.
const a = 20;
const b = 30;
const c = 40;
if (a < b) {
console.log("a");
} else if (a < c) {
console.log("c");
} else if (b < c) {
console.log("b");
} else {
console.log("b");
}
else if 를 사용해서 여러개의 조건문을 사용할 수 있다.
반복문(for문)
반복문은 조건에 맞으면 계속 반복한다.
기본구문은 for (초기화식; 조건식; 증감식) {실행문} (여기서 초기화란 변수이름과 값을 정해주는 것)
let height = [
{name:'kim', score:180},
{name:'lee', score:160},
{name:'park', score:170},
{name:'choi', score:150},
{name:'min', score:168},
]
for (let i = 0; i < height.length; i++) {
console.log(height[i].score)
}
// 180
// 160
// 170
// 150
// 168
i라는 변수에 0이라는 값을 주고, i가 height의 길이보다 작다면 중괄호를 실행한다. 그리고 i의 값에 1을 더한다.
i++ 은 i의 값에 1을 더한다는 뜻이다. 반복문이 돌 때마다 i의 값은 0에서 1씩 증가한다.