조건
?
조건이 true 시(truthy) 실행할 표현식:
조건이 false 시(falsy) 실행할 표현식
- truthy : falsy 로 정의되지 않은 모든 값
- falsy : false, 0, -0, 0n, "", null, undefined, and NaN
let greeting = person => {
let name = person ? person.name : `stranger`
return `Howdy, ${name}`
}
function example(…) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
leftExpr
??
rightExpr
왼쪽 피연산자가null
이거나undefined
일 경우 오른쪽 피연산자 반환
cf)||
( or 연산자) :null
,undefined
+거짓
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
let count = 0;
let text = "";
// ||
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42
console.log(message); // "hi!"
// ??
qty = count ?? 42;
message = text ?? "hi!";
console.log(qty); // 0
console.log(message); // ""
//Bad
const name = person.name;
const age = person.age;
//Object Destucting
const {name, age} = person;
const item = {type: 'pants', size: '26'};
const detail = {price : 3000}
// item객체, detail 에 있는 모든 속성을 가진 객체를 가지고 싶다면?
//Bad
const myPants = {
type : item.type,
size : item.size,
price : detail.price
}
//Good : Object.assign 활용
const myPants = Object.assign({},item,defail)
//Better : Spread Syntax
const myPants = {...item, ...detail}
// 가격만 5000원으로 바꾸고 싶다?
const myPants = {...item, ...detail , price: 5000}
const arr = ["a","b","c"];
//arr.push("d") 맨 뒤에 삽입
arr = [...arr, "d"]; // "a", "b", "c", "d"
//arr.unshift("e") 맨 앞에 삽입
arr = ["e", ...arr]; // "e", "a", "b", "c", "d"
// concat 배열을 합쳐 새로운 배열 반환
const arr2 = ["A","B"];
let combined = arr.concat(arr2);
combined = [...arr, "가", ...arr2];
참조의 유효성을 확인할 필요 없이 객체의 속성 확인 가능
참고 : 자바스크립트 프로처럼 쓰는 팁 ✨