Object Destructuring
Video
JavaScript Notes
JavaScript
//Why Destructuring (and ES6) is Awesome
let person = {
id: 123,
name: "Leslie",
dob: new Date("1985-01-01").valueOf(),
age: 44,
salary: 55000,
department: "Parks and Recreation",
hometown: "Pawnee"
};
savePersonES5(person);
savePersonES6(person);
// old way of doing this
function savePersonES5(someObj) {
let id = Date.now();
if (someObj.id) {
id = someObj.id;
}
let name = someObj.name;
if (!name) {
name = "Blank";
}
let dob = someObj.dob ? someObj.dob : new Date("2000-01-01").valueOf();
//save it in localStorage for later use
const KEY = "someRandomUniqueString";
let jsonStr = JSON.stringify({ id: id, name: name, dob: dob });
localStorage.setItem(KEY, jsonStr);
}
// new way of doing this
function savePersonES6({
id = Date.now(), //default value if it doesn't exist
name = "Blank", //default value if it doesn't exist
dob = new Date("2001-01-01").valueOf() //default value if it doesn't exist
}) {
const KEY = "someRandomUniqueString";
let jsonStr = JSON.stringify({ id, name, dob }); //allowed in ES6, if variable and property have the same name
localStorage.setItem(KEY, jsonStr);
}
Feedback
Submit and view feedback