Modern JS isn't as bad as you think

by @peferron

What is modern JS?

JS is an implementation of the ECMAScript standard.

ECMAScript 3 (1999) Last version supported by IE8
ECMAScript 5 (2009) Modern JS
ECMAScript 2015
ECMAScript 2016

Client-side: Windows XP support ended in April 2014.
Server-side: Node uses a modern JS engine (V8).
Can compile to older ES versions with Babel.

Today's app

Suggest days with nice weather for visiting San Francisco.

Written in ECMAScript 3.
We will update it to ECMAScript 2016 together.

How the app works

  1. HTTP GET sf-forecast.json
  2. Keep only the days with humidity below 90%.
  3. Write days to the webpage.

Look ma, no slides!

Open app.js in text editor.

Array methods

And others.

Open app.js and replace for loops with Array methods.

Arrow functions (1/2)

Arrow functions (2/2)

But arrow functions work out of the box.

Awkward workarounds exist:

This should work:

This should work:

But it doesn't.

Uncaught TypeError: Cannot read property 'name' of undefined

Open app.js and replace function with =>.

Template strings

Open app.js and replace string concatenation with interpolation.

Fetch API

Uses Promises instead of callbacks.

Open app.js and replace XMLHttpRequest with fetch.

async / await

Open app.js and replace callbacks with async / await.

Optional parameters (1/2)

How to make maximum humidity and minimum temperature configurable?


async function getLovelyDays(maxHumidity, minTemperature) {
  ...
}
            

var lovelyDays = await getLovelyDays(75, 80);
          

Unreadable for someone not familiar with the code.

Optional parameters (2/2)

This line was in our app before we moved to fetch.
Can you infer what true means?


request.open('GET', 'sf-forecast.json', true);
          

And now?


request.open('GET', 'sf-forecast.json', {async: true});
            

Open app.js and add the options maxHumidity and minTemperature.

Default parameter values

Open app.js and make options default to {}.

Destructuring

Deeply nested patterns are supported, but can hurt readability. Use responsibly.

Open app.js and use destructuring with default values for maxHumidity and minTemperature.

Before / after

  • 30 lines → 13 lines
  • Expresses intent much more clearly
  • Eliminates bug-prone mutation and manual loops

Other awesome features

Slides and source code

github.com/peferron/modern-js-talk

Credits