아래 글은 <한입 크기로 잘라 먹는 리액트> 강의를 참고한 내용입니다.
한입 크기로 잘라 먹는 리액트(React.js)
true가 아닌데 true로 반환하는 값
ex) [], {}, Infinity 등
false가 아니어도 false로 반환하는 값
ex) null, undefined, 숫자 0, -0, NaN, “”(빈문자열)
const getName = (person) => {
if (!person) {
//false Not => True
return "객체가 아닙니다";
}
return person.name;
};
let person;
const name = getName(person);
console.log(name);
왼쪽에서 오른쪽으로 계산하는 논리연산자의 순서를 이용한 문법으로,
단락회로 평가는 모든 피연산자와 연산자를 평가하지 않고서도 식의 결과가 결정되는 것을 의미한다.
const getName = (person) => {
const name = person && person.name;
return name || "객체가 아닙니다.";
};
let person;
const name = getName(person);
console.log(name);
비구조화할당(=구조분해할당)은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.
let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];
//비 구조화 할당, 위에랑 같은 결과
let [one1, two2, three3] = arr;
//더 단축 가능
let [one1, two2, three3] = ["one", "two", "three"];
//이렇게 기본값 설정 가능
let [one1, two2, three3, four = "four"] = ["one", "two", "three"];
let a = 10;
let b = 20;
let tmp;
tmp = a;
a = b;
b = tmp;
//이렇게 간단하게 스왑가능
[a, b] = [b, a];
let object = {
one: "one",
two: "two",
three: "three",
};
let one = object.one;
let two = object.two;
let three = object.three;
//비구조화 할당(키값을 기준으로 할당)
let {one, two, three} = object;
//이름을 바꿔서 할당 가능
let { one: score, two: two2, three } = object;
//역시 기본값 설정 가능
let { one: score, two: two2, three, name = "Misun" } = object;
spread연산자를 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있다.
const cookie = {
base: "cookie",
madeIn: "korea",
};
const chocochipCookie = {
base: "cookie",
madeIn: "korea",
topping: "chocochip",
};
const blueberryCookie = {
base: "cookie",
madeIn: "korea",
topping: "blueberry",
};
const strawberryCookie = {
base: "cookie",
madeIn: "korea",
topping: "strawberry",
};
//중복되는걸 스프레드연산자로 처리할 수 있음
const cookie = {
base: "cookie",
madeIn: "korea",
};
const chocochipCookie = {
...cookie,
topping: "chocochip",
};
const blueberryCookie = {
...cookie,
topping: "blueberry",
};
const strawberryCookie = {
...cookie,
topping: "strawberry",
};
const noTopingCookies = ["촉촉한쿠키", "안촉촉한쿠키"];
const toppingCookies = ["바나나쿠키", "블루베리쿠키", "딸기쿠키", "초코칩쿠키"];
const allCookies = [...noTopingCookies, "함정쿠키", ...toppingCookies];