Learning React [Day 1] - A Refresher on ES6

Posted on 29 Jun 2020 by Omar Sinan


Today I read chapters 1 and 2 of Learning React (2nd edition) by Alex Banks and Eve Porcello. Chapter 2 went over the developments in Javascript as of 2015 when ES6 was introduced. I learned a couple of new things that I hope you find useful :)

1. Arrow functions

One of the new features of ES6 is arrow functions. Their syntax is very simple and they can be very useful. Here is an example of a greet function using function expressions and its equivalent using arrow functions:

// function expression
const greet1 = function (name) {
    return `Hello there ${name}!`

// arrow function
const greet2 = (name) => `Hello there ${name}!`

As you can see, it looks much cleaner without the curly brackets and parenthesis for the function parameters. I'm excited to see practical use cases for this in the future.

2. Destructuring objects

This is one of my favorite features. In essence, you can extract relevant keys from an object and create local variables for them:

const house = {
    street: "ES6 wonderland",
    price: 20000,
    size: 300,
    built: 2014,

const { price, size } = house
// now you have price = 20000 and size = 300

Isn't that super cool? The dot notation can be avoided in this case by taking advantage of destructuring. This also applies to arrays. A very simple example would be destructuring arrays to extract the items at index 1 and 2 (0-indexed):

const fruits = ["apple", "orange", "peach", "grape"]
const [, fruit1, fruit2] = fruits
// now fruit1 = "orange" and fruit2 = "peach"

This will skip the first and last elements in the array because we ignored them by using commas without specifying a name.

3. The spread operator and rest parameters

Another useful feature that I can imagine myself using a lot is the spread operator. If you only want the first element of an array and don't care about the rest:

const fruits = ["apple", "orange", "peach", "grape"]
const [fruit1, ...rest] = fruits
// now fruit1 = "apple" and rest = ["orange", "peach", "grape"]

You could also use the spread operator when you have an indefinite number of arguments being passed to a function—rest parameters. Like... a function that adds up however many numbers you give it:

function add(...numbers) {
    let sum = 0
    for (const n of numbers) {
        sum += n
    return sum

And now guess what? you can call add: add(1, 2, 3, 4, 5) and it will return 15 🤯

That's it for day 1. I'm super stoked about this, and I can't wait to share more with you. Follow me on Twitter @oohsinan where I post cool stuff sometimes.