주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때에 사용합니다.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers) // 6
// ...numbers = 1 2 3 배열을 풀어서 넣는다.
// 즉,x=1 , y=2 , z=3
let parts = ['a', 'b'];
let lyrics = ['1', ...parts, '2', '3'];
console.log(lyrics); // ['1', 'a', 'b', '2', '3']
let arr = [1, 2, 3];
let arr2 = [...arr]; // arr.slice() 와 유사
arr2.push(4);
console.log(arr); //[1,2,3]
console.log(arr2); //[1,2,3,4]
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {foo: 'bar', x: 42}
console.log(mergeObj); // {foo: 'baz', x: 42, y: 13}
객체에서의 spread 복사 특징은 key값이 같으면 나중에 입력받은 객체의 value를 덮어씌운다.
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// a = "one"
// b = "two"
// manyMoreArgs = ['three', 'four', 'five', 'six']
파라미터를 배열의 형태로 받아서 사용할 수 있다. 파라미터 개수가 가변적일 때 유용하다.
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
sum(1,2,3) // 6
sum(1,2,3,4) // 10
const [a, b, ...rest] = [10, 20, 30, 40, 50];
// a = 10;
// b = 20;
// rest = [30,40,50];
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// a = 10;
// b = 20;
// rest = {c: 30, d: 40};
// 함수선언문
function sum (x, y) {
return x + y;
}
// 함수표현식
const subtract = function (x, y) {
return x - y;
}
// 화살표 함수
const multiply = (x, y) => {
return x * y;
}
function 키워드 대신 화살표(=>)를 사용.
매개변수가 한 개일 때, 소괄호(())를 생략할 수 있다.
// 매개변수가 한 개일 때, 소괄호를 생략할 수 있습니다.
const square = x => { return x * x }
// 위 코드와 동일하게 동작합니다.
const square = ( x ) => { return x * x }
// 단, 매개변수가 없는 경우엔 소괄호를 생략할 수 없습니다.
const greeting = () => { return 'hello world' }
함수 코드 블록 내부가 하나의 문으로 구성되어 있다면 중괄호({})를 생략할 수 있다.
이때 코드 블록 내부의 문이 값으로 평가 될 수 있으면 return 키워드를 생략할 수 있다.
const squre = x => x * x
// 위 코드와 동일하게 동작합니다.
const square = x => { return x * x }
// 위 코드와 동일하게 동작합니다.
const square = function (x) {
return x * x
}
주요 문법으로는 위의 것들이 있지만, 그 외에도 DESTRUCTURING , FOR OF , PROMISES , ASYNC / AWAIT , CLASSES , SYMBOL, SET AND MAP , GENERATORS AND MAPS 등이있으며 추가로 더 살펴볼 필요가 있다.