목차
- 변수선언
- spread 연산자
- 개체 비구조화 문법
var : 함수단위 스코프, 아래에 선언되어있어도 위에서 참조 가능(호이스팅)
let : 블록단위 스코프 : 선언시점부터 참조가능 : 변경 가능
const : 블록단위 스코프 : 선언시점부터 참조가능 : 재할당 불가 : 속성 변경은 가능
const PI = 3.14;
console.log(PI); // 출력: 3.14
// 재할당 시도
// PI = 3.1415; // 에러 발생: Assignment to constant variable.
// 객체의 속성 변경
const person = {
name: 'John',
age: 30
};
// 객체 전체를 재할당 시도
// person = { name: 'Jane', age: 25 }; // 에러 발생: Assignment to constant variable.
// 객체의 속성 변경은 가능
person.age = 31;
console.log(person); // 출력: { name: 'John', age: 31 }
껍데기를 벗기는 역할
배열이나 객체를 전개하거나 병합할 때 사용
// 배열 전개
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // 출력: [1, 2, 3, 4, 5, 6]
// 배열 병합
const newArr = [0, ...arr1, 4, 5];
console.log(newArr); // 출력: [0, 1, 2, 3, 4, 5]
// 객체 전개
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // 출력: { a: 1, b: 2, c: 3, d: 4 }
// 객체 병합
const newObj = { x: 0, ...obj1, y: 5 };
console.log(newObj); // 출력: { x: 0, a: 1, b: 2, y: 5 }
개체의 속성을 추출하여 변수로 사용하는 것
// 객체 생성
const person = {
name: 'John',
age: 30,
};
// 객체 비구조화 문법을 사용하여 속성 추출
const { name, age } = person;
console.log(name); // 출력: John
console.log(age); // 출력: 30
// 함수 정의
function printPersonInfo({ name, age }) {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
}
// 함수 호출
printPersonInfo(person);