Destructuring Objects
With destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data.
const person = {
first: "John",
last: "Doe",
links: {
social: {
twitter: "https://twitter.com/john.ca",
facebook: "https://facebook.com/johndoe"
},
web: {
blog: "https://johndoe.com"
}
}
};
const { twitter, facebook } = person.links.social;
Rename the variables as you destructure
const { twitter: tweet, facebook: fb } = person.links.social;
Set fallback or default value
const settings = { width: 300, color: "black" };
const { width = 100, height = 100, color = "blue", fontSize = 25 } = settings;
Destructuring arrays
const details = ["John Doe", 123, "johndoe.com"];
const [name, id, website] = details;
console.log(name, id, website);
Destructuring comma separated string
const data = "Basketball,Sports,90210,23,John,Doe,cool";
const [itemName, category, sku, inventory] = data.split(",");
Destructuring into Rest - an example using rest parameter
const team = ["John", "Harry", "Sarah", "Keegan", "Riker"];
const [captain, assistant, ...players] = team;
Swapping Variables with Destructuring
let inRing = "Hulk Hogan";
let onSide = "The Rock";
[inRing, onSide] = [onSide, inRing];
To make order of arguments independent, wrap these 3 arguments in , and then pass an object in tipCalc function so that it destructures the object.
function tipCalc({ total = 100, tip = 0.15, tax = 0.13 }) { return total + tip * total + tax * total; } const bill = tipCalc({ tip: 0.2, total: 200 }); console.log(bill);
What is we don't pass anything in tipcalc?
function tipCalcDefault({ total = 100, tip = 0.15, tax = 0.13 } = {}) { return total + tip * total + tax * total; } const newBill = tipCalcDefault(); console.log(newBill);
0 comments:
Post a Comment