Faster Programming (with ES6): Destructuring and Arrow Function (Part 2/4)

Avatar von Alex Aulbach

This series is about how to program „faster“. It is not, however, about typing code faster but to write less code in the first place. It saves time but also you have to read less code and the effort to maintain it sinks in the long run (more about it in the introduction). In part 2 I’ll show you how to use destructuring and the Arrow Function. 

Destructuring – Mapping Shorthands (ES6)

I bet you have already seen destructuring, but don’t know it by this name. These are two examples of how it works in general:

var a = 1;
var b = 3;
[a, b] = [b, a];

Destructuring assumes that, if you name variables equally, you mean the same. That can be used to rename things:

const values = {
    a: 'a',
    b: 'b'
};
const { a, b: x, c: y = 'c' } = values;
console.log('a == ' + a, 'x == ' + x, 'y == ' + y);
// OUTPUT
a == a
x == b           // b renamed to x
y == c           // y is 'c', because c was not set in data, so it takes the default

This is still a bit theoretical.

Let’s show a before-after example. We use destructuring often in React projects. You grab parameters from the arguments with it. Without destructuring this looks like this:

// we assume here a person-object, that looks more or less like this:
persons = [
    {
        first = 'Alex',
        last = 'Aulbach',
        location = {
            city = 'Würzburg',
            country = 'Germany',
        }
    },
    { ... more persons ... }
]

If we want to display this variable then in the scope of React, it looks like this:

// we have a call in react, looks for example so:
...
persons.foreach(person => (
	...
	<PrintPerson person={person} />
	...
)

// and PrintPerson looks so
const PrintPerson = (props) => (
  <div>
    <p>First Name: {props.person.first}</p>
    <p>Last Name: {props.person.last}</p>
    <p> Adress:
      {props.person.location.city},
      {props.person.location.country}
    </p>
  </div>
);

The first step to improve it:

// Simplify the call
persons.foreach(person => (
    ...
    <PrintPerson {person} />
    ...
}
 
// And cause I need only the props.person here, I can grep it out of the props:
const PrintPerson = ({ person }) => (
  <div>
    <p>First Name: {person.first}</p>
    <p>Last Name: {person.last}</p>
    <p> Adress:
      {person.location.city},
      {person.location.country}
    </p>
  </div>
);

Much better, but we can improve it a little bit more:

const PrintPerson = ({
    person: {
        first,
        last,
        location: {city, country}
    }
}) => (
  <div>
    <p>First Name: {first}</p>
    <p>Last Name: {last}</p>
    <p> Adress:
      {city},
      {country}
    </p>
  </div>
);

This construction grabs only those values necessary from the props into flat local variables. With this, the code is much more maintainable. I don’t need to read the entire function PrintPerson to understand what part of props it works. It’s enough to read the definition.

If you compare it with the first example it’s less code but the code becomes more complex. It introduces some „strange mechanics“ to map things on the right side to the left. When written/read over and over you will soon get used to it.

Destructuring is an important shorthand for everything, here is a link if you want to dig deeper.

Sidetrack: Use a Prettyfier/Linter

Every programmer has a different style to write code. Some will write the function-definition into one line. Others make only linebreaks when it looks ugly. And some of us prefer a space after a colon. The number of possibilities is endless.

But it is important to write similar things in a similar way. It makes the code „shorter“ or „faster“ in a rather unexpected way: you can read the code faster. Which makes you also a faster programmer.

To achieve that linters and prettyfiers come into play. It’s a must, even for small projects, it improves readability of code a lot. It’s so liberating when your IDE formats your code while you are writing it. And removes all the discussions about the right syntax for every new project.

Arrow Function (The Fat Arrow) (ES6)

Perhaps you have already seen the Fat Arrow / Arrow Function. For me it’s the best way to make code shorter; but also more unreadable.

The main reason for the existence of the fat arrow is the different handling of this depending on the scope. The general syntax looks like this:

(param1, param2, …, paramN) => { statements }

Here is an example (examples taken from developer.mozilla.org):

var persons = [
  'Samantha',
  'Liebhold',
  'Janet',
  'Rosa'
];
 
console.log(persons.map( (person) => { return person.length } ));
//                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the fat arrow
// output [ 8, 8, 5, 4 ]

ES6 lets us simplify it to

console.log(persons.map( (person) => person.length ));

because the function part contains only a return of an expression. If the function has only one parameter, you can also remove the brackets:

console.log(persons.map( person => person.length ));

For me as a former PHP developer quite unreadable but that is only the „first grade of shortening“. You can then combine the Arrow Function with destructuring from above and here ES6 reveals its beauty! For example, you can return objects:

console.log(persons.map( person => ({count: person.length}) ));
// [ { count: 8 }, { count: 8 }, { count: 5 }, { count: 4 } ]

Set brackets around the return-object. Otherwise, it’s a function-statement not a return-expression! See above. For more experienced programmers a spoiler: destructuring reveals its true power only together with TypeScript. More on this in part 4 of this series.

Use default Params

var persons = [
  'Samantha',
  undefined,
  'Janet',
  undefined
];
console.log(persons.map( (person = 'Q') => person.length ));
// [ 8, 1, 5, 1 ]

That (defaults, deconstruction, renaming…) works also for the parameter-list:

var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();                // 6
f([2,2]);           // 8
f([0,0], {x: 111}); // 111

A more Practical Example

// again our person from above
var persons = [
  'Samantha',
  'Liebhold',
  'Janet',
  'Rosa'
];

Task: sum up the number of letters of each name.

var totalLength = persons.reduce(
                          function(summedLength, name) {
                                  return summedLength + name.length
                          }, 0);

– versus –

var totalLength = persons.reduce(
                          (summedLength, name) =>
                                  summedLength + name.length, 0);

I used here Array.reduce(). You see, that this reduces code, even it’s only 20 chars. But that adds up, 20 chars here, 30 chars there…

Summary

My goal is to show you methods to reduce your code and with this help you to program faster. It’s not only reducing the lines of code but increasing its maintainability in a software lifecycle. So, maintenance of software should – and under normal circumstances also will – last as long as possible. And so the code is much more often read than written. Faster programming doesn’t mean, that you will write code faster.

In part 3 we will have a look at „magic getters and setters“.

Avatar von Alex Aulbach

Kommentare

Eine Antwort zu „Faster Programming (with ES6): Destructuring and Arrow Function (Part 2/4)“

  1. Lesetipp: Faster Programming (with ES6): Destructuring and Arrow Function (Part 2/4) https://t.co/Hx9gV2rn3Z https://t.co/w36MxqpRmS

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


Für das Handling unseres Newsletters nutzen wir den Dienst HubSpot. Mehr Informationen, insbesondere auch zu Deinem Widerrufsrecht, kannst Du jederzeit unserer Datenschutzerklärung entnehmen.