[Javascript] Modern operators
Updated:
Destructuring
- 배열 또는 객체에서 특정 원소, property를 간단하게 저장하는 방식
// Destructuring Arrays
const [x, y, z] = arr;
const [i, , [j, k]] = nested;
const [p = 1, q = 1, r = 1] = [8, 9];
[main, secondary] = [secondary, main];
// Destructuring Objects
const { name, openingHours, categories } = restaurant;
const {
name: restaurantName,
openingHours: hours,
categories: tags,
} = restaurant;
const { menu = [], starterMenu: starters = [] } = restaurant;
const {
fri: { open: o, close: c },
} = openingHours;
Spread Operator (…)
- 배열, 객체의 원소, property를 말그대로 펼쳐서 대입하는 방식
const newArr = [1, 2, ...arr];
console.log(...newArr);
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
console.log(menu);
// Iterables: arrays, strings, maps, sets. NOT objects
const str = "mindflip";
console.log(...str);
// Objects
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: "Guiseppe" };
const restaurantCopy = { ...restaurant };
Rest Pattern and Parameters
- spread operator 를 반대로 적용
- 원소를 배열, 객체로
// 1) Destructuring
const [a, b, ...others] = [1, 2, 3, 4, 5];
const [pizza, , risotto, ...otherFood] = [
...restaurant.mainMenu,
...restaurant.starterMenu,
];
// Objects
const { sat, ...weekdays } = restaurant.openingHours;
// 2) Functions
const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) sum += numbers[i];
console.log(sum);
};
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);
Short Circuiting (&& ||)
console.log("---- OR ----");
// Use ANY data type, return ANY data type, short-circuiting
console.log(3 || "mindflip"); // 3
console.log("" || "mindflip"); // mindflip
console.log(true || 0); // true
console.log(undefined || null); // null
console.log(undefined || 0 || "" || "Hello" || 23 || null); // Hello
const guests2 = restaurant.numGuests || 10;
console.log("---- AND ----");
console.log(0 && "mindflip"); // 0
console.log(7 && "mindflip"); // mindflip
console.log("Hello" && 23 && null && "mindflip"); // null
// Practical example
if (restaurant.orderPizza) {
restaurant.orderPizza("mushrooms", "spinach");
}
restaurant.orderPizza && restaurant.orderPizza("mushrooms", "spinach");
Nullish Coalescing Operator (??)
restaurant.numGuests = 0;
const guests = restaurant.numGuests || 10;
// Nullish: null and undefined (NOT 0 or '')
const guestCorrect = restaurant.numGuests ?? 10;
console.log(guestCorrect);
Optional Chaining (?.)
- 배열의 원소, 객체의 property가 있는지 체크
// WITH optional chaining
console.log(restaurant.openingHours.mon?.open);
console.log(restaurant.openingHours?.mon?.open);
// Example
for (const day of days) {
const open = restaurant.openingHours[day]?.open ?? "closed";
console.log(`On ${day}, we open at ${open}`);
}
// Methods
console.log(restaurant.order?.(0, 1) ?? "Method does not exist");
console.log(restaurant.orderRisotto?.(0, 1) ?? "Method does not exist");
// Arrays
console.log(users[0]?.name ?? "User array empty");
ref :
Udemy JS complete course
Leave a comment