본문 바로가기

JavaScript

ES6

 

1. 스프레드 문법 (Spread Syntax)

1.1 함수 호출에서의 사용

스프레드 문법(...)은 배열이나 객체의 요소를 하나씩 풀어서 전달할 때 사용된다.

function sum(x, y, z) {
    return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 출력: 6
  • ...numbers: 배열의 요소를 하나씩 분리하여 함수의 인자로 전달.
  • 주의:
    sum(numbers); 
    
    위처럼 전달하면 numbers가 배열로 전달되며, 나머지 매개변수(y, z)는 undefined가 된다.
    결과적으로 NaN이 반환된다.

1.2 배열 복사 및 합치기

스프레드 문법은 배열을 복사하거나 합치기에도 유용하다.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const copiedArr = [...arr1];
const mergedArr = [...arr1, ...arr2];

console.log(copiedArr); // [1, 2, 3]
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
  • 복사: copiedArr는 arr1의 값을 복사하지만, 원본 배열(arr1)에는 영향을 주지 않는다.
  • 합치기: mergedArr는 두 배열을 합치며, 원본 배열에는 영향을 주지 않는다.

1.3 객체 복사 및 병합

스프레드 문법은 객체의 속성을 복사하거나 병합할 때도 사용된다.

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 14 };

let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };

console.log(clonedObj); // { foo: 'bar', x: 42 }
console.log(mergedObj); // { foo: 'baz', x: 42, y: 14 }
  • 중복 키: 병합 시 중복된 키는 가장 마지막에 선언된 값으로 덮어쓴다.
    위 예시에서 foo는 obj2의 값인 'baz'로 덮어씀.

2. 구조 분해 할당 (Destructuring Assignment)

2.1 배열의 구조 분해

배열의 각 요소를 분리하여 변수에 할당할 수 있다.

const arr = [1, 2, 3];
const [a, b, c] = arr;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

2.2 객체의 구조 분해

객체의 속성을 분리하여 변수에 할당할 수 있다.

const obj = { name: 'Alice', age: 25 };
const { name, age } = obj;

console.log(name); // Alice
console.log(age); // 25
  • 기본값 설정:
  • const { height = 170 } = obj; console.log(height); // 170
  • 함수에서의 활용: 구조 분해 할당은 함수의 매개변수에서도 자주 사용된다.
  • function greet({ name, age }) { console.log(`Hello, my name is ${name} and I am ${age} years old.`); } greet({ name: 'Alice', age: 25 });

3. 화살표 함수 (Arrow Function)

3.1 기본 문법

화살표 함수는 function 키워드 대신 =>를 사용한다.

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

3.2 특징

  • 간결한 문법: 함수 본문이 한 줄일 때 중괄호와 return 키워드를 생략할 수 있다.
  • const square = x => x * x; console.log(square(4)); // 16
  • 매개변수 하나일 때 소괄호 생략 가능:
  • const greet = name => `Hello, ${name}`; console.log(greet('Alice')); // Hello, Alice
  • this 바인딩: 화살표 함수는 this가 정의된 환경의 값을 그대로 유지한다.
    일반 함수는 호출되는 시점에 따라 this가 달라질 수 있다.

4. Rest 문법

...는 스프레드 문법 외에도 Rest 문법으로 사용될 수 있다.
Rest 문법은 함수의 매개변수나 구조 분해에서 나머지 요소를 하나의 변수로 모으는 데 사용된다.

function sum(...numbers) {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 10
  • 매개변수로 나머지 값 모으기:
    const [first, ...rest] = [1, 2, 3, 4];
    console.log(first); // 1
    console.log(rest);  // [2, 3, 4]
    

 

'JavaScript' 카테고리의 다른 글

JS브라우저 DOM  (0) 2024.05.24
실습  (0) 2024.05.24
클로저 - 원래 스코프 내부에서는 외부로 접근 가능한거 아니야?  (0) 2024.05.22
객체  (0) 2024.05.22
클로저  (0) 2024.05.22