강의
[패스트캠퍼스 강의] 연산자와 구문
seulye
2024. 12. 31. 14:11
* 부정 연산자
console.log(!{})
=> false
console.log(![])
=> false
빈 배열도 true이다.
* 논리 연산자
console.log('A' && 'B' && '')
=>
console.log('A' && 'B' && 'C')
=> C
console.log(0 || 1)
=> 1
console.log(function () {} || undefined || '')
=> f () {}
console.log(false || 0 || NaN)
=> NaN
* Nullish 병합 연산자
const n = 0;
const num2 = n ?? 7;
console.log(num2);
=> 0
console.log(null ?? undefined);
=> undefined
console.log(null ?? 1 ?? 2);
=> 1
null과 undefined 만 넘어감.
* 전개 연산자(Spread Operator)
const a = [1,2,3];
const b = [4,5,6];
const c = a.concat(b);
console.log(c);
=> [1,2,3,4,5,6]
const d = [...a,...b];
배열의 대괄호를 날려주는 역할을 한다.
객체 데이터의 중괄호를 날려주는 역할도 한다.
* 구조 분해 할당
const arr = [1,2,3];
const [a,b,c] = arr;
console.log(a,b,c);
=> 1 2 3
let b = 0
let c = 0
const arr = [1,2,3]
;[,b,c] = arr
console.log(b,c)
=> 2 3
const arr = [1,2,3];
const [a, ...rest] = arr;
console.log(a,rest);
=> 1 [2,3]
배열 구조 분해 할당은 순서가 중요.
const {a,b,c} = obj;
// x 값이 없으면 4
const {x=4} = obj;
// 이름을 heropy로 변경
const {a:heropy} = obj;
console.log(heropy);
const {c, ...rest} = obj;
console.log(rest);
=> {a:1, b:2}
객체 데이터 구조 분해 할당은 정말 많이 쓰인다.
* 옵셔널 체이닝
const user = undefined
console.log(user?.name)
이것도 정말 많이 쓰이는..!! 꼭 필요한 상황에서만 사용하기.
* Switch 문
function price(fruit){
switch(fruit){
case 'Apple':
p=1000
break
case 'Banana':
p=2000
break
default:
p=0
}
return p
}
console.log(price('Apple'))
=> 1000
switch문은 if문으로 대체될 수 있다.
* 반복문
// user은 객체 데이터
for (const key in user){
console.log(key)
}
do while 문은 while문과 달리 거짓이어도 한번은 실행됨.
do {
console.log(n);
n += 1;
} while (n < 4);