Last week we looked at some ECMAScript 2015 basic concepts which you can review in this article.
We also tried playing around with these concepts, but were not very successful, here I will post some better examples.
Destructuring
Destructuring may seem a bit overkill at first glance, but it is very useful when getting methods out of large objects or arrays.
A more comprehensive list of examples can be found over at MDN (developer.mozilla.org).
Here is a simple example of getting values out of an array:
let myArray = [0, 1, 2, 3, 4, 5]; let [ x, y, ...rest ] = myArray; console.log(x); // logs 0 console.log(y); // logs 1 console.log(rest); // logs [2, 3, 4, 5]
In this case you can see the use of the rest pattern as well, that is that we assign “rest” to be the rest of the values that have not been extracted already through destructuring.
Here we extract values out of an object:
let myObject = { firstname: "Sara", lastname: "Winter", middlename: "Veronika" } let { firstname, middlename } = myObject; console.log(firstname); // logs Sara console.log(middlename); // logs Veronika
This is the equivalent of writing:
console.log(myObject.firstname); // logs Sara console.log(myObject.middlename); // logs Veronika
Where this comes into good use is when you are working with large objects where you do not necessarily know all of the available properties.
Variable names can also be altered this way, which may be useful when names are very long or not very descriptive for the current purpose:
let { firstname: first, middlename: middle } = myObject; console.log(first); // logs Sara console.log(middle); // logs Veronika
Destructuring functions
function sayName({ first, second, last="Winter" }){ console.log("My full name is " + first + " " + second + " " + last); } sayName({ first: "Sara", second: "Veronika" }); // logs My full name is Sara Veronika Winter sayName({ first: "Sara" }); // logs My full name is Sara undefined Winter sayName({ first: "Sara", second: "Veronika", last: "Summer" }); // logs My full name is Sara Veronika Summer
console.log(`My full name is ${first} ${second} ${last}`);
function myFunctionWithManyArgs(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); myFunctionWithManyArgs(var1, var2, var4, var5, var6, var7, var8 ); // oops! we forgot to send var3... which can lead to some pretty weird errors.
function loopArgs( ...args ){ for (const arg of args) { console.log(arg); } } loopArgs("Sara", "Veronika"); // logs Sara, then Veronika loopArgs("Sara"); // logs Sara loopArgs("Sara", "Veronika", "Summer"); // logs Sara, then Veronika, then Summer