Code Patterns In Modern JavaScript

March 21, 2017 — Rob Welan

ES6 provides a significant amount of improvements to what is currently the most in-use language on the planet.

It can take a long time to adopt to unfamiliar new ways.

Here are some short cuts to get you familiar with functions in ES6. We are comparing JavaScript ES5 ways to JavaScript ES6 ways.

You'll need a modern browser's console to play with all the code. Buckle up, because we're going to go fast!

Hello World

ES5
function helloWorld () {  
    console.log('Hello World');
}

helloWorld();  
ES6
const helloWorld = () => {  
    console.log('Hello World');
}

helloWorld()  
ES6 Optimised
const helloWorld = _ => console.log('Hello World')

helloWorld();  

Concatenation

ES5
var sH = 'Hello';  
var sW = 'World';  
var sE = '!';

function writeLine (a, b, c) {  
    return (a + ' ' + b + c);
}

writeLine(sH, sW, sE);  
ES6
const sH = 'Hello';  
const sW = 'World';  
const sE = '!';

const writeLine = (a, b, c) => {  
  return (a + ' ' + b + c);
}

writeLine(sH, sW, sE);  
ES6 Optimised
const sH = 'Hello',  
      sW = 'World',
      sE = '!'

const writeLine = (a, b, c) => `${a} ${b}${c}`

writeLine(sH, sW, sE)  

Function Currying

ES5
var outer = 'hello';  
var inner = 'world';

function getString (outer) {  
  return function (inner) {
    return outer + ' ' + inner;
  }
}

getString(outer)(inner);  
ES6
const outer = 'hello';  
const inner = 'world';

const getString = (outer) => {  
  return (inner) => {
    return outer + ' ' + inner;
  }
}

getString(outer)(inner);  
ES6 Optimised
const outer = 'hello',  
      inner = 'world'

const getString = outer => inner => `${outer} ${inner}`

getString(outer)(inner)