JavaScript Essential
비교 comparison operator
const a = 1;
const b = 2;
a !== b
a <= b
a >= b
논리 연산자 logical operator
const a = 1 === 1;
const b = 'AB' === 'AB';
const c = false;
console.log('&&: ', a && b && c);
console.log('||: ', a || c);
console.log('!: ', !a);
console.log('!:', !c);
- &&: and 모든 조건이 참이여야 "참"
- ||: or 한 조건이라도 참이면 "참" 모두 거짓이면 "거짓"
- !: not 조건의 반대 결과를 보여줌 참이면 "거짓", 거짓이면 "참"
삼항 연산자 ternary operator
const a = 1 < 2;
if (a) {
console.log('맞다');
} else {
console.log('틀리다');
}
console.log(a ? '맞다' : '틀리다');
조건문 If Else (If statement)
- 두 가지 이상의 조건을 넣은 조건문을 만들 수 있다.
function random() {
return Math.floor(Math.random() * 10);
}
const a = random();
if (a === 0) {
console.log('a is 0');
} else if (a === 2) {
console.log('a is 2');
} else if (a === 4) {
console.log('a is 4');
} else {
console.log('rest...');
}
조건문 Switch statement
- 조건이 다양할 시 사용하기 유용하다.
- break; 를 꼭 넣어서 해당 조건을 만족시, 조건문을 나와야 한다.
- 마지막은 break 문 필요 X
switch (a) {
case 0:
console.log('a is 0');
break;
case 2:
console.log('a is 2');
break;
case 4:
console.log('a is 4');
break;
default:
console.log('rest...');
}
반복문 For statement
- for (시작조건; 종료조건; 변화조건) {}
<ul></ul>
const ulEl = document.querySelector('ul');
for (let i = 0; i < 3; i += 1) {
const li = document.createElement('li');
li.textContent = `List-${i + 1}`;
ulEl.appendChild(li);
}
변수 유효 범위 Variable Scope
- var, let, const
- let, const: 블럭 레벨
- const 주사용
- 재할당이 필요할 때 let 사용
- var: 함수 레벨 (유효 범위가 더 넓음)
- 메모리 누수가 발생 할 수 있다
- 사용을 권장 하지 않음
형 변환 Type conversion
- ==: 동등연산자, 형 병환이 일어나면 값만 비교해서 의도 하지 않은 true가 나올 수 있음
- ===: 일치연산사, 자료의 타입까지 같아야 함
- Truthy: 참 같은 값
- true, {}, [], 1, 2, "false", -12, "3.14" ...
- Falsy: 거짓 같은 값
- false, "", null, undefined, -0, 0, Nan
let a = 1;
let b = '1';
a === b
a == b
c = 0;
d = false;
c == d
c === d