Bite-sized screencasts for React
and frontend developers

The 10 min ES6 course for the beginner React Developer

posted on: 28-mar-2018

The famous 80–20 Pareto principle is also true when it comes to the learning React & ES6 relationship. ES6 came with more that 75 new features, but from what I’ve seen, I found myself needing less than 20% of them in more that 80% of the cases.

note : just to avoid any confusions and without going into very geeky stuff JavaScript is the same thing as ECMAScript (or ES). ES6 = ES5 + some new features, so both ES6 and ES5 are Javascript. The main difference lies in the set of supported features.

For me it was quite confusing two years ago when I first moved from good old Angular 1, and “pure” ES5 Javascript, to React and seeing in some tutorials things like arrow functions or destructor statements. It was not clear, what was from React and what from ES6.

Actually, for the first week or so, I was almost sure that you could write something like {name} only in React.

Not even by far this is intended to be a complete run-through of all of the new features. It is only the “stuff” from ES6 that I’ve seen used in the vast majority on the React code. So … here we go:

Let and const

In the “old” Javascript (meaning ES5), to declare a variable we were using the keyword var. Given some black magic thing called Javascript hoisting we could use a variable before declaring it.

// ES5
console.log(myVar); // prints out undefined
var myVar = 10;

This can lead to some behavior. Not anymore. In ES6, via the let or const keywords you must explicitly declare something before using it.

// ES6
console.log(myVar) // ReferenceError myVar is not defined
let myVar = 10

As you can imagine, the difference the between const and let is that you cannot change a const after it gets its initial value.

// ES6
let x = 10
const y = 20
x = 25 // all is ok
y = 30 // TypeError: Assignment to constant variable.

No more semicolons

From ES6 both ECMAScript 6 and all the related tools perfectly support automatic semicolon insertion. As a consequence, ECMAScript 6 coders nowadays can get rid of nearly all semicolons and remove some clutter from their code.

//ES5
var theNumber = 10;
console.log(theNumber);

//ES6 - look ma’ no semicolons
let theNumber = 10
console.log(theNumber)

Not quite a life changing feature , but for sure a nice one, especially if you had at some point a love affair with things like CoffeeScript.

Arrow functions

To make a function in ES5 you will have to write something like:

// ES5
var sum = function(a, b) {
   return a + b
}

In ES6 you can fast type it by using :

// ES6
const sum = (a, b) => {return a + b}

And , if you have a very simple one line function , you can even drop the return keyword:

// ES6
const sum = (a, b) => a + b // a one line arrow function will auto return the result of last used value

Another thing to keep in mind is that arrow functions are automatically bound to their upper scope:

function DogWorldContext() {
  this.age = 0

  setInterval(function growUp() {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithStandardFunction = new DogWorldContext()
// will print Nan every second, as the growUp is a standard function it has it's own this keyword context.
function DogWorldContext() {
  this.age = 0

  setInterval(()=> {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithArrowFunction = new DogWorldContext()
// will print 1,2,3 ... every second

The arrow functions don’t have their own this. The this context becomes the parent one, in our case the DogWorldContext.

Destructor statements

To quote from developer.mozilla.org the destructor statements makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

It is quite a common case the need to extract a attribute from a object into a separate entity. Let’s say we have the following code:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
alert(this.props.user.name + " " + this.props.user.age);

So to make it easier to read we could have something like:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
var name = this.props.user.name;
var age = this.props.user.age;
alert(name + " " + age);

But with ES6 we could use destructor statements and say:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name} = this.props.user
const {age} = this.props.user
alert(name + " " + age)

Or with just one line:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name, age} = this.props.user
alert(name + " " + age)

Object Literals

Somehow in the same idea we have the Object Literals. They allow us to define key-value pairs with less code.

// ES5
str = "HELLO"
number = 20
obj = {
   str: str,
   number: number
}

In E6 this can be easy translate into:

// ES6
str = "HELLO"
number = 20
obj = { str, number} // will make obj = {str: "HELLO", number: 20}

Classes, constructors and methods

We did not have class as a keyword in the “old Javascript”. So, in order to create a simple Dog class, you could make a workaround like this one:

// ES5
function Dog(name, weight){
  this.name = name;
  this.weight = weight;
}

Dog.prototype.speak = function(){
	alert("Woof, woof … my name is: " + this.name);
};

// Instantiate new objects with ‘new’
var dog = new Dog("Spike", 25);

// Invoke methods like this
dog.speak(); // alerts “Woof, woof … my name is: Spike”

You could also define a base object, and other approaches, but the bottom line was that you did not have classes “out of the box”. So meet the ES6 classes and objects:

//ES6
class Dog {
   constructor(name, weight) {
      this.name = name
      this.weight = weight
   }
   speak() {
     alert("Woof, woof … my name is: " + this.name)
   }
}
const dog = new Dog("Spike", 25)
dog.speak()

Class inheritance and React

Like in the case of Classes, in ES5 you could achieve the inheritance mechanism by doing some workarounds. But we have the extends keyword in ES6.

// ES6 
class Chihuahua extends Dog {
	shaking() {
		alert("look at me ! I’m shaking !")
	}
}

const miniDog = new Chihuahua("Mini Spike", 1)
miniDog.shaking() // I have my own methods
miniDog.speak() // but I’ve also inherited the ones from my upper classes

Also like in the case of the class keyword, extends is only a sugar syntax, but is quite useful in the React code, as it let us move from a code like this :

var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

to a more clear version like:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Also keep in mind that if you use extends to define your React components the getInitialState() method is replaced with just a simple this.sate = … statement in the constructor of the class. You can see more about this here.

Filter

Let’s say we have the following array.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If you would want to create a new array only with the values that are greater than 10, in ES5 circumstances you would need a for loop, or something similar (eg: see the each() from jQuery).

Well, in ES6, we can use the filter function to go through all the values from the array and keep only the ones that meet the requirements of a function.

//ES6

const notDigits = numbers.filter( function(value) {return value > 9})
console.log(notDigits) // prints out [20,90,22,33]

// or using arrow functions
const notDigits1 = numbers.filter( (value) =>  {return value > 9}
// and we can alos use the default return or the  arrow functions
const notDigits2 = numbers.filter( (value) =>   value > 9 )

.. and Map

Even if it’s from the “old” ES5, map is one of the most underused functions of Javascript. All the time you need to loop through a array , you can use map.

Let say we have the same array as in the previous example.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If we just want to display the array just use map:

numbers.map( (n) => console.log(n))
// and you also have a second parameter, the index
numbers.map( (n, index) => console.log(n + ' is the ' + index + ' value from the array ') )
// or if we want to generate a second array by maping 
const double= numbers.map( (n) => n*2 )

You will see map(), over and over in React, all the time we will need to show a list of items:

render() {
	return(
  this.props.items.map( (item, key) =>  <p key={key}>{item}</p>
  )
} 

So, these are the most common ES6 features that I use when writing React code. Disclaimer: the list is highly biased and subjective :). In no way it was intended to diminish the usefulness of other ES6 features. As said earlier, there are many others ES6 that are not covered here, but these concepts should allow you to easily upgrade from ES5 React to the new ES6 syntax and understand what comes from React and what comes from the new ES6 features. Cheers and happy coding!