[SeSACx코딩온] 구조 분해 할당, 스프레드 연산자(...), 논리 연산자(&&, ||)
구조 분해 할당, 스프레드 연산자, 논리 연산자
1. 구조 분해 할당 (Destructuring Assignment)
(1) 배열 구조 분해
- 기본 구조 예시
const arr1 = [1, 2, 3, 4, 5];
const [one, two, three, four, five] = arr1;
console.log(one, two, three, four, five); // 1 2 3 4 5
- 값이 없는 경우
undefined
가 할당됩니다.
const arr2 = ['a', 'b', 'c'];
const [x, y, z, alpha] = arr2;
console.log(x, y, z, alpha); // a b c undefined
(2) 변수 값 교환
- 제 3의 변수를 사용하지 않고도 두 변수의 값을 쉽게 교환할 수 있습니다.
let num1 = 1;
let num2 = 2;
[num2, num1] = [num1, num2];
console.log(num1, num2); // 2 1
(3) 기본 값 설정
- 구조 분해 할당 시 기본 값을 설정하여 값을 할당할 수 있습니다. 값이 없는 경우도 가능합니다.
const lists = ['apple', 'grape'];
const [f1, f2, f3 = 'orange'] = lists;
console.log(f1, f2, f3); // apple grape orange
(4) 객체 구조 분해
- 객체 구조 분해 시, 변수 이름은 객체의 키와 일치해야 합니다.
const obj = {
title: '엘리먼트',
content: 'fun',
num: 5
};
const { num, title, content, star = 1000 } = obj;
console.log(num, title, content, star); // 5 엘리먼트 fun 1000
console.log(obj); // { title: '엘리먼트', content: 'fun', num: 5 }
// . 표기법
console.log(obj.title); // 엘리먼트
// [] 표기법
console.log(obj[`title`]); // 엘리먼트
- (object) : {key와 value} 에서
value
가 없으면undefined
가 출력됩니다.
const { a1, b1, c1 } = obj;
console.log(a1, b1, c1); // undefined undefined undefined
(5) 함수 매개변수에 적용
구조 분해 할당을 함수 매개변수에 적용하여 함수 내에서 객체 속성을 쉽게 사용할 수 있습니다.
const lectureInfo = {
name: 'Coding on',
part: 'web',
leader: 'Kim',
};
function getInfo({ name, part, leader }) {
return `${name} 강의는 ${part} 개발을 공부합니다. 수업의 리더는 ${leader} 입니다.`;
}
const result = getInfo(lectureInfo);
console.log(result);
2. 스프레드 연산자 (Spread Operator)
(1) 정의
// 기존의 방식
const d = `HELLO`.split(``);
console.log(d); // [ 'H', 'E', 'L', 'L', 'O' ]
// spread 연산자 ( ... ) : 배열값을 전부 나눠서 새로운 배열로 합쳐줌.
const c = [...`HELLO`]; // [ 'H', 'E', 'L', 'L', 'O' ]
console.log(c);
(2) 배열 합치기
스프레드 연산자를 사용하여 배열의 요소를 쉽게 복사하거나 새로운 배열에 합칠 수 있습니다.
const a = [1, 2, 3];
const b = [4, 5];
const spread = [...a, ...b];
console.log(a + b); // 1,2,34,5
console.log(spread); // [1, 2, 3, 4, 5]
(3) 문자열을 배열로 변환
스프레드 연산자를 사용하여 문자열을 개별 문자로 나눌 수 있습니다.
const c = [...'HELLO'];
console.log(c); // ['H', 'E', 'L', 'L', 'O']
(4) 객체 합치기
객체의 속성을 복사하거나 새로운 객체에 합칠 수 있습니다.
const chip = {
base: 'chip',
company: 'lotte',
};
const potatoChip = {
...chip, // chip 객체 넣음
flavor: 'potato',
};
console.log(chip); // { base: 'chip', company: 'lotte' }
console.log(potatoChip); // { base: 'chip', company: 'lotte', flavor: 'potato' }
(5) 특정 값을 제외한 나머지 반환
const icecream = {
company: 'lotte',
flavor: 'choco',
price: 1000,
};
const {flavor, ...abc} = icecream;
console.log(flavor); // choco
console.log(abc); // { company: 'lotte', price: 1000 }
onst values = [10, 20, 30, 40, 50, 60];
function get(a, b, ...rest) { // 순서대로 읽고 나머지 값들은 rest에 넣음.
console.log(a, b); // 10 20
console.log(rest); // [ 30, 40, 50, 60 ]
}
get(...values) // values를 분해하여 get 함수 매개변수로 넣음.
function get2(a, b, c, ...rest) {
console.log(a, b, c); // 10 20 30
console.log(rest); // [ 40, 50, 60 ]
}
get2(...values)
3. 논리 연산자 (Logical Operators)
코드 흐름은 기본적으로 왼쪽 -> 오른쪽으로 진행합니다.
- OR: 만약 왼쪽이 true일 경우 OR 조건이므로 나머지는 확인하지 않는 원리입니다.
- AND: AND조건이므로 마지막까지 검사하기 때문에 마지막 값이 출력되는 원리입니다.
(1) OR (||) 연산자
OR 연산자는 첫 번째 true 값을 출력합니다.
const x = 5;
const result = x || 100;
console.log(result); // 5
(2) AND (&&) 연산자
AND 연산자는 모든 조건이 true인 경우 마지막 값을 출력합니다.
const x = 5;
const y = 7;
const result2 = x < y && 'abc';
console.log(result2); // abc
(3) Falsy 값 처리
Falsy 값 (undefined, null, 0, false, ‘’, NaN)을 간단히 처리할 수 있습니다. OR 연산자이므로 왼쪽에 값이 있으면 이미 true이므로 나머지를 확인하지 않고 왼쪽이 결과로 나오는 원리입니다.
// userColor 값이 있는 경우
let userColor = 'red';
let defaultColor = 'blue';
let currentColor = userColor || defaultColor;
console.log(currentColor); // red
// userColor가 선택되지 않아 값이 없는 경우
let userColor = undefined;
let defaultColor = 'blue';
let currentColor = userColor || defaultColor;
console.log(currentColor); // blue