Passing an object as 2 parameters:
The two most used data structures in JavaScript are
Object
and
Array
.
Objects allow us to create a single entity that stores data items by key, and arrays allow us to gather data items into an ordered collection.
But when we pass those to a function, it may need not an object/array as a whole, but rather individual pieces.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.
Array Destruturing
let [firstName, surname] = "Ilya Kantor".split(' ');
Ignoring content
// second element is not needed
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
Works with any iterable on the right-side
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
Assign to anything at the left-side
let user = {};
[user.name, user.surname] = "Ilya Kantor".split(' ');
alert(user.name); // Ilya
Complete example:
const things = ['red', 'basketball', 'paperclip', 'green', 'computer', 'earth', 'udacity', 'blue', 'dogs'];
const [one, , , two, , , , three] = things;
const colors = [one,two,three];
console.log(colors);
[ 'red', 'green', 'blue' ]
Looping with .entries()
let user = {
name: "John",
age: 30
};
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
alert(`${key}:${value}`); // name:John, then age:30
}
and for maps
let user = new Map();
user.set("name", "John");
user.set("age", "30");
for (let [key, value] of user) {
alert(`${key}:${value}`); // name:John, then age:30
}
The rest “…”
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(name2); // Caesar
// Note that type of `rest` is Array.
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2
Default values
let [firstName, surname] = [];
//this are not errors
alert(firstName); // undefined
alert(surname); // undefined
// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // Anonymous (default used)
// runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];
alert(name); // Julius (from array)
alert(surname); // whatever prompt gets
Object destructuring
const gemstone = {
type: 'quartz',
color: 'rose',
carat: 21.29
};
const type = gemstone.type;
const color = gemstone.color;
const carat = gemstone.carat;
console.log(type, color, carat);
quartz rose 21.29
Another Example:
const point = [10, 25, -34];
const [x, y, z] = point;
console.log(x, y, z);
10 25 -34
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
const gemstone = {
type: 'quartz',
color: 'rose',
carat: 21.29
};
const {type, color, carat} = gemstone;
console.log(type, color, carat);
quartz rose 21.29
Error NAN
const circle = {
radius: 10,
color: 'orange',
getArea: function() {
return Math.PI * this.radius * this.radius;
},
getCircumference: function() {
return 2 * Math.PI * this.radius;
}
};
let {radius, getArea, getCircumference} = circle;
getArea = NAN
Calling
getArea()
will return
NaN
. When you destructure the object and store the
getArea()
method into the
getArea
variable, it no longer has access to
this
in the
circle
object which results in an area that is
NaN
.
Other destructuring Example
// changed the order in let {...}
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
let options = {
title: "Menu"
};
let {width: w = 100, height: h = 200, title} = options;
alert(title); // Menu
alert(w); // 100
alert(h); // 200
let options = {
title: "Menu",
width: 100,
height: 200
};
// only extract title as a variable
let { title } = options;
alert(title); // Menu
Example from https://www.linkedin.com/learning/learning-ecmascript-6
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
<script type="text/babel">
var [first,fourth]=["calama","chuqui","san pedro","toconao","ollague","la serena"];
console.log(first);
console.log(fourth);
var vacation = {
destination: "Chile",
travelers: 2,
activity: "skiing",
cost: 4000
};
function vacationMarketing({destination, activity}) {
return `Come to ${destination} and do some ${activity}`
}
console.log(vacationMarketing(vacation));
</script>
<title>Destructuring Assignment</title>
</head>
<body>
</body>
</html>
Sources: