Cart

Your Cart is currently empty.

Fill Cart with Goods

JavaScript – ECMAScript 6 Getting Started

Introduction:

JavaScript undoubtedly is one of the most famous programming language of our times. GitHub now hosts more JavaScript projects than any other language so are the stats from stack overflow. JavaScript is growing rapidly and dwarfing many older well established programming languages like Java, C#, C++ and many others. Today you cannot just manipulate DOM(Document Object Model) of the web browser with JavaScript you can develop apps(React Native) and write server backends(Node.js / Express JS) in JavaScript. Mastering JavaScript today will turn you into a true Full Stack developer.

History:

JavaScript was deigned by Brendan Eich in 10 days while he was working for Netscape. Plan was design a scripting language for the browser, as Java was hot back in the day they ended up naming the language JavaScript even though it had nothing to do with Java.

JavaScript is one of those language which makes it easy to get started with but is extremely hard to master. There are a lot of developers out there who claim to be JavaScript developers but lack the deep understanding of the language. Developers coming from other languages expect things certain way and end up blaming the poor language design.

We believe understanding of the language is of paramount importance if you want to be considered a serious programmer.

This article will just focus on the ES 6 version of the language and assumes some understanding of JavaScript language and some experience with programming in general.

ECMA stand for European Computer Manufacturers Association, it is the association that is in charge of setting standard for the JavaScript programming language. ECMAScript 6 or ES6 OR ECMAScript 2015 refers to the standard of JavaScript programming language that was published in 2015.

Let keyword

Previously JavaScript relied on var keyword to declare variables but how it handled scope confused a lot of programmers, unintending overriding of value declared in var was common. Consider the following code

var x = 10;

if(true){
    var x = 200;
}

console.log(x);

 

The output of the program is surprisingly 200, if when the scope of the variable x in the if was local somehow its value persisted even after the block.

Now consider the same scenario with the let keyword

let x = 10;

if(true){
   let x = 200;
}

console.log(x);

 

Now the output is 10 as expected. Obviously there are many ways to work around this issue but let keyword provides an excellent way to manage variables within their lexical scopes.

Const Keyword

Const keyword is another excellent addition which in a nutshell like let keyword it allows you to declare a variable and enforce lexical scoping but the value of this variable cannot be changed.

const y = 100;

y = 4; //will not work

 

Attempting to do so will raise an exception.

const obj = new Object();

obj.name = "some name";

obj.type = "some type";

var obj2 = new Object();

obj2.name = "2nd Name";

obj2.type = "2nd Type";

obj.name = obj2.name; // this would work

console.log(obj.name);



obj = obj2; //this wont work

obj.name = "some other name" //this will work

 

A point to note here is that the contents that are held within the object can be changed but the object reference cannot be changed.

Template Literals

Template means a preset format and literal means to be interpreted as was written. Template literal in JavaScript allows you to manipulate strings as is keep respecting new lines and giving ability to embed expressions within the strings.

Previous way to concatenate and add variables to a String.

Var value = 10

Var myString = 'This is a string showing value of : ' + value + 'to be used in code. \n Thank you'

New syntax:

Var myTemplateLiteralString = `This is a string showing value of : ${value} to be used in code.

Thank you`.

Notice JavaScript uses the back ticks to define Template Literals.

 

Spread Operator

Spread operator is used to expand arrays. Spread operator copies the data of the array or arrays and hand you a new array. Spread operator is readily used in Redux in React and generally a lot in functional programming in JavaScript. It can also be used to turn the elements of array to arguments of a function call.

Consider the example below:

var arrayOne = [1,2,3,4,5]

var arrayTwo = [6,7,8,9]



var arrayThree = [...arrayOne, ...arrayTwo ];

 

This would concatenate the two arrays.

 

Default function parameters

A lot of languages already have this feature and finally it has come to JavaScript. It basically lets you specify the default values of function parameters if in case they are called without the parameter values.

Consider the code below

 

function add(valueOne = 1, valueTwo = 2){
   return valueOne + valueTwo;
}

add(3,4); //would return 7
add(); //would return 3, as 1 & 2 will be used as default values.
add(5); //would return 7

 

Destructuring

Destructuring is a fun way to do assignments in ES 6. Consider the following examples:

var carArray = ['Toyota Corolla', 'BMW Series 7', 'VolksWagen Polo', 'Mercedes S 500', 'Honda Civic', 'Audi A6', 'Kia Picanto'];

var [toyota, , , , honda, , ] = carArray;

console.log(toyota);
console.log(honda);

In the example above we are able to destructure and array and assign variables values from the array by using a simple destructuring syntax.

Consider another example of an Object literal in this case.

var toyotaCorolla = {
    make: 'Toyota Corolla',
    model: 2016,
    engine: '1800 cc Turbo',
    price: 5000,
    currency: 'USD',
    description: 'Car is in excellent condition',
    tyres: ['One', 'Two', 'Three', 'Four'],
    driven: 55000
};

var {make, price, description} = toyotaCorolla;
console.log(make);
console.log(price);
console.log(description);

function carInfo({make, price, driven}){
    console.log(`The car is ${make}, is driven ${driven} kms price is ${price}`)
}

carInfo(toyotaCorolla);

Just like array we are able to destructure the object literal and assign values from it using a short syntax. Plus in the function call we can send an entire object as an argument and destructure it in the implementation which is an awesome feature. Destructuring is readily used in React JS framework and in modern JavaScript make sure you understand it well.

Enhanced Object Literals

Consider the following code

 

var carObject = {
   drive: function(km){
         console.log('Drive the car ' + km);
      }
   park: function(){
        console.log('Park the car');
      }
   drift: function(angle){
        console.log('Drift the car at following angle ' angle);
      }
};

This can be simplified as following in ES 6 JavaScript

var carObject = {
   drive(km){
         console.log('Drive the car ' + km);
      }
   park(){
        console.log('Park the car');
      }
   drift(angle){
        console.log('Drift the car at following angle ' angle);
      }
};

 

Arrow functions

Arrow functions is one of the best features in ES 6 JavaScript. They make your code concise and also make you cleanly handle the scope of this variable.

Consider the following code:

var addLordToMyName = function(name){
    return 'Lord ' + name; 
} 
console.log(addLordToMyName('Assad')); //This would print Lord Assad

Now consider the ES 6 Arrow function version of the same code

var addLordToMyNameArrow = name => 'Lord ' + name;

console.log(addLordToMyNameArrow('Assad'));

Both the functions have same results, the arrow function is more concise and clear. Above we declare a variable addLordToMyNameArrow variable that holds the function. ‘name’ is the function parameter, if you only have one function parameter you don’t need to use brackets. If we had more than one variable we would have used a bracket like this (firstName, secondName). The => is the arrow function sign in fact its from where it takes its name. If we have only one line we don’t need to use parentheses in arrow function. Also if you have one line you can also drop the return statement.

With that arrow functions handles the scope of the variable this without having you to bind it specifically. Which we will discuss in another blogpost.

Generators

Generator functions are a new edition in ES 6, they allow you to pause the execution of function in the middle and resume it afterwards enabling you to write Async code in a synchronous manner. Generator functions are used readily in Redux Saga, having a good understanding of Generator functions would take you places. We will dedicate another blog post to Generators in near future, its internals how it works and how you can make it work for you.

Generator functions use the following syntax:

function* funcName(){
    yield;
    yield;
    yield;
}

At each yield statement the execution of the function stops there and hands over the yielded value. Consider the code below:

function* abcFunc(){
    yield 'a';
    yield 'b';
    yield 'c';
    yield 'd';
}

var doSomething = abcFunc();
console.log(doSomething.next()); //prints {value: "a", done: false} 
console.log(doSomething.next()); //prints {value: "b", done: false} 
console.log(doSomething.next()); //prints {value: "c", done: false} 
console.log(doSomething.next()); //prints {value: "d", done: false} 
console.log(doSomething.next()); //prints {value: undefined, done: true}

//to get the value you can call doSomething.value()
//when done is returned true you know that the generator function has finished.

Symbols

Symbols are a new primitive type in ES 6 JavaScript. They are created using a factory function and each call to Symbol returns a new unique object that does not coincide or collide with previous values.

const ID = Symbol('mySymbol');
typeOf Symbol() //returns symbol

 

The argument string is just an optional parameter descriptive string, it has no other purpose. Symbols are tokens that can be served as unique values. For example you can use them as constants to define car types, consider the code below:

//ES5 Way
const SUV = 'SUV';
const SEDAN = 'Sedan';
const COUPE = 'Coupe';
const CONVERTIBLE = 'Convertible';

//ES6 Way
const SUV = Symbol('Suv');
const SEDAN = Symbol('Sedan');
const COUPE = Symbol('Coupe');
const CONVERTIBLE  = Symbol('Convertible');

//Even if someone else create var mySUV = 'SUV' or even const mySUV = Symbol('SUV') it would never collide in thw switch statement.

 

Iterables and Iterators

Iterable and Iterator are protocols that define a new iteration behavior in ES6.

Iterable JavaScript objects define their own iteration behavior.

Iterator: Standard way to produce sequence of values.

If an object implements these an iterator can be used to iterate over its values. You can call next method on the object to get values from the iterable object, once done it would return done in an object as true.

Maps

Map holds key value pairs, any value can be used as a key or as value not just the string, you can use arrays, numbers etc. You can use map in the following ways:

var cars = new Map();
cars.set('foo', 'boo'); //to set 
cars.get('foo'); //to get

OR

var cars = new Map([
    ['SUV', 'Land Cruiser'],
    [new Date(), 'Awesome Date'],
    ['symbol', new Symbol()], //Anything can be key-value 
    [123 , 'One Two Three']
  ]);

 

Sets

Sets are similar to Maps except they only store unique values. Consider the code below:

const set = new Set(['suv', 'sedan', 'bicycle']);
const set2 = new Set().add('suv').add('sedan').add('bicycle'); 

var randomIntArray = [3,3,4,4,4,3,3,4,5,6,6,7,8,9,9,3,5,5,9]; 
var numberSet = new Set(randomIntArray); 

console.log(randomIntArray.length); //prints 19
console.log(numberSet.size); //prints 7

 

For…of loop

For…of loop is a new addition in ES 6, it is similar to for…in loop but it lets you directly iterate over iteratable object properties.

for(item of set){
    console.log(item)
}

 

Promises

Promises is a new concept in ES 6 JavaScript they make asynchronous code more manageable and understandable. Promises and Async programming in ES 6 JavaScript warrants an entire post, we will just have a birds eye view of promises in this post. Promises lets you  steer away from the traditional callback hell that had plagued JavaScript codebases previously. Coming from callback hell promises do feel like a breath of fresh air. The code below is a standard code for an async function that returns a promise object.

function asyncFunction() {
    return new Promise(
        function (resolve, reject) {
            resolve(result);
            reject(error);
        });
}

To call the previously defined function you use the following code template:

asyncFunction()
.then(result => {  }) // Do something when a promise is resolved
.catch(error => {  }); // Do something when a promise has been rejected

.then() can be chained to add custom logic on succession of completion of each .then() function.

Async Await

Async Await is another feature of ES 6 that enable you to write Async code in synchronous manner. Making your code more easy to understand and manage. Consider the following code below:

const delayInSeconds = sec =>{
    return new Promise(
        resolve => setTimeout(resolve, 1000 * sec)
    )
};

const printToConsole = async ()=> {
    await delayInSeconds(2);
    console.log('Printed after 2 seconds');
    await delayInSeconds(3);
    console.log('Printed after 5 seconds');
    await delayInSeconds(3);
    console.log('Printed after 8 seconds');
}

printToConsole();

Async await makes code even more readable than Promises in another blog post we will create our own async await so that you can understand what really happens under the hood.

Classes

ES 6 JavaScript finally has a similar syntax for working with classes under the hood JavaScript it is using the same Prototypical inheritance. Consider the following code:

class Car {
    constructor(name, model) {
        this.name = name;
        this.model = model;
    }
    toString() {
        return `${this.name}, and model ${this.model}`;
    }
}

class Toyota extends Car { //inherit using the extends keyword
    constructor(name, model, color) {
        super(name, model);
        this.color = color;
    }
    toString() {
        return super.toString() + ' in ' + this.color;
    }
}

const corolla = new Toyota('Corolla', '2018', 'white'); //Initialize through constructor
corolla.toString(); // Prints "Corolla, and model 2018 in white"
corolla instanceof Car; // true
corolla instanceof Toyota; // true

typeof Toyota; // "function"

Classes are extended using the extends keyword, the constructor is named constructor unlike Java where it is class name. Under the hood it uses the same constructor functions to implement classes, thats the reason you see typeof Toyota as a function.

 

Summary

We have barely scratched the surface of new ES 6 JavaScript features and there is a lot to it. A separate post can be written for each of the above mentioned features. In coming weeks we will be discussing each of the these in depth. We will also be creating a small video related to this blogpost and mentioning the URL here soon. There are some ES 6 features that we have deliberately left out because they required more explanation or were a little complex for an introductory level post. Sit tight and keep visiting our website for more posts.

Comments

Thomas

Your arrow function section is incorrect. You’re comparing a function declaration to a function expression. Function declarations are loaded before any code is executed while function expressions are loaded only when the interpreter reaches that line of code. You would be able to call the first function (declaration) at any time while the second arrow function would throw an error if you tried to call it before it was defined.

var addLordToMyNameArrow = name => ‘Lord ‘ + name;

is the same as

var addLordToMyName = function(name) { return ‘Lord’ + name; }

Another example:

alert(addLordToMyName(‘Max’)); // Lord Max

function addLordToMyName(name) { return ‘Lord’ + name; }

alert(addLordToMyNameArrow(‘Max’)); // error: Uncaught TypeError: addLordToMyNameArrow is not a function

var addLordToMyNameArrow = name => ‘Lord’ + name;

I hope this helps.

October 21, 2019

asadkhan

Thanks for pointing out Thomas 🙂

October 24, 2019