What’s new in ES2015 (ES6)

I could not been more happy when I heard ES6 will be officially launched. This new version of JavaScript brings a bunch of new String, Array or Object functions, new code declarations and code styles and also native Classes.

Don’t get me wrong, but I think this new version of JavaScript will start a new ear of writing applications and I assume because of that JavaScript will have been used way more often than it used to be – and I dare to say, it may even dare to aim of becoming the most used programming language overall.

writing javascript
Photo by Clément H on Unsplash

But enough of words, let’s look at what the new JS version brings us in more detail.

Table of contents:

  1. Ditching the var
  2. Template strings
  3. Default function parameters
  4. Arrow functions
  5. Destructing assignments
  6. Object literals
  7. Spread operator
  8. Classes
  9. Array helpers
  10. String helpers

1. Replacing var with const and let

One of the small changes that will affect everybody (in a positive sense) who codes in javascript is going to be this.

Up until now we’ve been used to declaring variables with var declaration, some people did not declare variables at all, they just write:

radius = 10
items = 20

result = radius * items

I dare to say, var declaration will be eliminated completely in the future by the const and let declarations.

1.1 const

As the name suggests, it is going to be possible to declare a variable, that is not changing its data type during the runtime of scripts.

Example:

const RADIUS = 3.14;
const MAX_INPUT_LENGTH = 255;
const max_seconds = 60;

As you can see, the naming convention is entirely up to you. You can use camel, snale, kebab or wheatever case you like.

Me personally, I will stick to UPPERCASE, because it is just a convention from other programming languages.

Example #2:

const MAX_INPUT_LENGTH = 255;

if(someConditionIsTrue()) {
    MAX_INPUT_LENGTH = 999;
}

The example #2 above will throw an error, because a constant is something that does not change.

Example #3:

const items = [];
const info = {};

if(someConditionIsTrue()) {
    items.push("apple");
    info["apple"] = "healthy";
}

The example #3 will not throw an error though. It is because the variable did not change its value – it is still the reference to the same array, but the contents of the variable changed – and this is how it’s intended to work.

Don’t worry, you’ll get used to that.

1.2 let

The let declaration is very similar to the const above, however it will be possible to override its value (so if you used let-s in your whole project, it will be alright).

Example #1:

let name = "ivan";

if(shouldCensoreTheName()) {
    name = Math.Random();
}

The example above will not throw an error, because let is allowed to be overridden.

Example #2:

for(let i = 0; i <= 10; i++) {
    console.log(i); // => will log 1, 2, 3, ...etc
}

console.log(i); // => the variable i is undefined

If you’re wondering about the example above, one of the advantages of let as well as const declarations is that they are scoped only to the nearest block (usually enclosed by { and }).

Example #3:

<script>
    {
        const MAX_ITEMS = 10;
        console.log(MAX_ITEMS); // => will log 10 into the console
    }

    console.log(MAX_ITEMS); //will throw a ReferenceError, because the variable has not been defined in the scope we are accessing it
</script>

2.Template strings

This is a feature you’re gonna definitely fall in love with 😍. If you’ve been used to doing this:

Example #1:

var name;

var firstName = "Ivan";
var lastName = "Hanak";

name = [firstName, lastName].join(" ");

//or 

name = firstName + " " + lastName;

//or even 

name = firstName + (shouldShowLastName() ? " " + lastName null);

…your life will become more way easier!

With a new syntax, you will be able to concatenate two variables with ease.

Example #2:

var firstName = "Ivan";
var lastName = "Hanak";

const name = `${firstName} ${lastName}`;

The fundamentals of the new syntax is `${variable}` and once a string is surrounded in backticks, everything starting with a dollar sign and enclosed in curly brackets will be treated as a variable!

Example #3:

const fullName = 'Ivan Hanak';
const innerHTML = `My name is ${fullName}`;

3. Default function parameters

Example #1:

function doAction(param1, param2, param3) {
    param1 = param1 || null;
    param2 = param2 || 20;
    param3 = param3 || true;
}

…is going to be a thing of the past. The new javascript version will support default parameters on function arguments, exactly as you might know them from the other programming languages.

Example #2:

function doAction(param1 = null, param2 = 20, param3 = true) {
    
}

4. Arrow functions

This is something you’re going to have to get used to.

But, once you do, you will absolutely love it!

Arrow functions bring two very important updates:

  • this will no longer be bound to the function body
  • the declaration will be so much shorter

Example #1:

const fakeFunction = function () {
    this.item = 10;

    setTimeout(() => {
        console.log(this.item); // => will log 10
    }, 10);
};

Example #2:

const multiply = (a, b) => a * b;
const makeDouble = a => a * 2;
const censoreText = (textToBeCensored) => {
    return textToBeCensored.replace("twat", "--censored");
};

As you can see, the new way of declaring functions will be much more quick and efficient. But that’s not all. Scroll down to see new Array functions and when mixed with for example with .find(), ,findIndex() or .filter() you will be amazed what it can do!

5. Destructing assignments

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Example #1:

let a, b, rest; 
[a, b] = [10, 20]; 
console.log(a); // 10 
console.log(b); // 20

[a, b, …rest] = [10, 20, 30, 40, 50]; 
console.log(a); // 10 
console.log(b); // 20 
console.log(rest); // [30, 40, 50]

6. Object literals

This one will ease working with object, imagine the following situation:

Example #1:

const name = "Warren";
const lastName = "Buffett";
const age = 93;

const getInvestor = (name, lastName, age) => {
    return {
        name: name, 
        lastName: lastName, 
        age: age
    };
};

Did you just needed to repeat the name of every single variable? So ES6 will allow you to skip the whole : value part, when a key and the passed value parameter both have the same name, like to:

Example #2:

const name = "Warren";
const lastName = "Buffett";
const age = 93;

const getInvestor = (name, lastName, age) => {
    return {
        name,
        lastName,
        age
    };
};

Easy-peasy-🍋-squeasy, what do you say? 😉

7. Spread operator

You’re gonna absolutely loove this one! “Three dot” operator as it is called will be really helpful assistant when performing various oeprations, consider the following examples:

//old way
const newArray = oldArray.concat(["apple"])
//new way
const newArray = [...oldArray, "apple"];

Pretty neat, don’t you think? 😉

Also, many of us would welcome similar workflow with Objects as well, for example, if it would be possible to accomplish the following:

//the same with cloning objects
//old way
const newObject = Object.assign(oldObject, {});

//new way
//const newObject = {...oldObject};

…our life would become that much more easier! Never mind, maybe sometime in the future 🙂 .

EDIT: 22nd July, 2019 – guess what! Now it’s live. Object spread operator was made available in ES9! Go and check it out within the special ES9 article!

8. Classes

“A syntactic sugar” as some people call it, but if you decide to use it, it will make your code that much more readable. Imagine this when coding react, for example:

Example #1: – react old syntax

const React = require("react");

const myComponent = React.createClass({
    helper: function () {
        return "";
    },
    componentDidMount: function () {},
    componentWillUnmount: function () {},
    render: function () {}
});

Example #2: – react class syntax

import React, {Component} from 'react';

class MyComponent extends Component {

    static someClassVariable = null;

    componentDidMount() {
        //do stuff
    }

    render() {
        return null;
    };
};

Neat, isn’t it? 😉

9. Array helpers

And if you haven’t loved anything that I said you’re gonna love, you’re gonna absolutely looove this one!

Have you ever used a for loop to find an item inside array? Did you copy a library from stack overflow to accomplish that? Or did you just write a function to do it yourself?

Well, not anymore my friends!

JavaScript will contain – as I call it – the best functions ever – and I will bet with you – those functions will be the most used ones by everybody, the functions are as follows:

  • .find()
  • .findIndex()
  • .includes()
  • .every()
  • .some()
  • .filter()
  • .reduce()
  • .reduceRight()

Examples:

//find an item inside an array
const names = [].find(name => name === "ivan");

//find an array index of an item being looped
const names = [].findIndex(name => name === "ivan");

//check if the array contains an item
const isInArray = ["ivan", "peter", "philip"].includes("ivan");

//check if every element in the array meets the specified condition
const everythingDivisableByTwo = [2, 4, 6].every(number => number % 2 === 0);

//check if at least one element within the array meets the specified condition
const atLeastOneIsDivisableByTwo = [1, 2, 3, 4, 8].some(number => number % 2 === 0);

//filters out items from the array that does not meet the specified condition
const onlyNumbersDivisableByTwo = [1, 2, 3, 4, 5].filter(number => number % 2 === 0);

//merges the array into a single value
const total = [1, 2, 3, 4].reduce((a, b) => a+b); // => will return 10

Unbelievable, right? 🤩

10. String helpers

The same as with arrays, a String interface got overhauled as well.

There were added a couple of new methods:

  • .startsWith()
  • .endsWith()
  • .includes()
  • .repeat()
  • .fromCodePoint()
  • .codePointAt()
  • .normalize()

Final thoughts

What do you say? Did like like all the new stuff that is coming? 😍 The only advantage of this is very little browser support, however we can start using everything mentioned above right now – babel transpiller is going to take care of making sure, our code works perfectly in every browser.

Of course, the transpilled code will be that much more heavier in file size, but we will not even notice, time will pass and everything will be implemented in every browser in no time!

If you’d like to deep dive into much more detail about everything mentioned, check out very comprehensive articles on MDN:

On the other hand, if you like the information put down within blog article like this one, check out my archive about the topic JavaScript.

And also if you liked this article, don’t forget to share it with people you like (or maybe also people you don’t like, maybe you’ll became friends! 😆 ).

I will be doing more articles like this in the future and if you want to get notified about them and everything else I release, subscribe to my newsletter right here.

Anyways, thanks for reading and I’ll see you in the next article! 🤓

Yours in coding,

Ivan