react 개발을 위해서 꼭 필요한 JS 문법 중, ES6 문법에 대해 숙지해야 한다.
얕은 복사의 개념과, 이를 방지해야 하는 이유에 대해 알아보자!
예전에는 변수하면 모두 var 키워드를 이용했지만, 이제는 const(상수)와 let(변수)을 이용한다.
const: 재할당 X, 내부 속성값은 수정 가능
let: 재할당 O
*둘 다 block level scope를 가진다.
block-level-scope?
모든 코드 블록(함수, ifans, for문, while문, try/catch문 등) 내에서 선언된 변수는 코드 블록 내에서만 유효하며 코드 블록 외부에서는 참조할 수 없다. 즉, 코드 블록 내부에서 선언한 변수는 지역 변수이다.
if (true) {
var a = 1;
// const a = 1;
}
console.log(a);
object는 key-value pair!
// 객체 선언 방법
const person = {
name: '르탄',
age: 21,
company: 'sparta coding club',
doSomething: () => {},
}
const name = '르탄';
const age = 21;
/** 단축속성 : key - value가 일치하면 생략해요. */
// 변경 전
const person = {
name: name,
age: age,
company: 'sparta coding club',
doSomething: function(){},
}
// 변경 후
const person = {
name,
age,
company: 'sparta coding club',
doSomething: function(){},
}
const obj1 = { value1: 10 };
const obj2 = obj1; // 얕은 복사
const obj3 = JSON.parse(JSON.stringify(obj1))
obj1.value1 += 1;
// 결과를 예상해보세요! 같이 해봅시다.
console.log(`obj1:`, obj1); // 11
console.log(`obj2:`, obj2); // 11
console.log(`obj3:`, obj3); // 10
결론적으로 const obj2 = obj1; 이런 방식의 복사(얕은 복사)는 주의해야 한다.
의도치 않은 변경이 일어날 수 있다!!
// 일반 텍스트
`string text`
// 멀티라인
`string text line 1
string text line 2`
// 플레이스 홀더를 이용한 표현식
`string text ${expression} string text`
= 구조분해 할당
// 구조분해 할당
// person 객체 안에 있는 값들이 구조해제되어 각각 변수에 할당된다.
const person = {
name: '르탄',
age: 21
}
const { name, age } = person;
console.log(`${name}님, ${age}살이시네요!`); // 르탄님, 21살이시네요!
// 함수의 입력값 또한 각각 구조가 해제되어 각각 변수에 할당된다.
// 이 패턴을 자주 쓸 예정!!! 기억해두자
const person1 = {
name: '혜린',
age: 27
}
function hello({name, age}) {
console.log(`${name}님, ${age}살이시네요!`);
}
hello(person1); // 혜린님, 27살이시네요!
// 객체 케이스와 마찬가지로 배열도 구조분해 할당이 이루어진다.
const testArr = [1, 2, 3, 4, 5];
const [val1, val2, val3, val4, val5, val6] = testArr;
console.log(val2); // 2
console.log(val6); // undefined
// 이런식으로도 할당 가능!
let [name] = ['Tom', 10, 'Seoul'];
let [, age] = ['Tom', 10, 'Seoul'];
let [, , region] = ['Tom', 10, 'Seoul'];
let [, , , height=150] = ["Tom", 10, "Seoul"];
console.log(name, age, region, height); // Tom 10 Seoul 150
전개연산자 ... 를 이용해서 다음과 같이 활용할 수 있다.
let [name, ...rest] = ['TOM', 10, 'Seoul'];
console.log(name, rest); // TOM [ 10, 'Seoul' ]
console.log(name, rest[0], rest[1]); // TOM 10 Seoul
let names = ['혜린', '바보'];
let students = ['똥개', ...names]
console.log(names[0], names[1]); // 혜린 바보
console.log(students); // [ '똥개', '혜린', '바보' ]
let tom = {
name: 'Tom',
age: 10,
region: 'Seoul'
};
let steve = {
...tom,
name: 'Steve'
};
console.log(tom, steve)
// { name: 'Tom', age: 10, region: 'Seoul' }
// { name: 'Steve', age: 10, region: 'Seoul' }
function 다양한 표시 방법
const sum1 = (x, y) => x + y;
const sum2 = (x, y) => ({ x: x, y: y });
const sum3 = (x, y) => {
return { x: x, y: y };
}
const sum4 = function (x, y) {
return { x: x, y: y };
}
function sum5(x, y) {
return { x: x, y: y };
}
// + 잘못된 예시
const sum = (x, y) => { x, y };
console.log(sum1(1, 2), sum2(1, 2));