DEV Community

Discussion on: What's your favorite addition to ES2015+

Collapse
 
jckuhl profile image
Jonathan Kuhl

Destructuring

So before ES2015 and destructuring we had this:

var width = this.state.width;
var height = this.state.height;
var position = this.state.position;

or for arrays

var width = this.state[0];
var height = this.state[1];
var position = this.state[2];

Now it's prettier with

const { width, height, position } = this.state;

or for arrays:

const [ width, height, position ] = this.state;

It comes really handy when iterating over Object.entries, which gives you an array like:

[ [key1, value1], [key2, value2] . . . . [keyN, valueN] ]

Because you can do this:

const entries = Object.entries(obj);
for([key, value] of entries) {
   // do something with the key and value
}

Or this

Object.entries(obj).filter(([key, value]) => {
    if(value > 10)
       return key;
});

It's nice, like python packing/unpacking:

value1, value2 = sys.argv[1:2]

I mean, sure it can get ugly:

const {
   width,
   height,
   position,
   color,
   font,
   kerning,
   linespacing,
   border,
   background,
   textcontent
} = this.state;

but that goes for anything in programming.

Collapse
 
laurieontech profile image
Laurie

Definitely my favorite!