The ECMAScript 2015 aka ES6, is the 6th edition of the ECMAScript language specification standards. What ES6 did to Javascript was what Java8 did to Java. ES6 came with many new features to enhance the existing language and many new concepts to write clean and concise code.
Here are some additions in ES6
1. let & const (Block Scope without Hoisting )
If you’ve coded in Javascript before 2016, you know how vulnerable the var keyword made the applications. Using it outside a function was a suicide but even within a function, it created problems due to hoisting. Now, what was hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
So no matter where you declare var, it will always be moved to the top of its enclosing function. So any block within the function will still see the same variable. This doesn’t leave any space to have scopes.
To tackle this problem, ES6 introduced let. Any variable defined with let will be scoped to the most recent block it's defined in. Therefore, will not be seen outside.
For better understanding, copy this code in an empty file and open file in browser
<html><body>Check console logs</body> <script> window.onload = () => {let letVariable = 10; var varVariable = 10;console.log(`initial value letVariable = ${letVariable}`) console.log(`initial value varVariable = ${varVariable}`){ let letVariable = 20; var varVariable = 20;console.log(` intermediate value letVariable = ${letVariable}`); console.log(` intermediate value varVariable = ${varVariable}`); }
letVariable = letVariable + 30; varVariable = varVariable + 30;console.log(`final value letVariable =${letVariable}`) console.log(`final value varVariable = ${varVariable}`)} </script></html>
What do you expect to see? Think of an answer before looking at console logs.
Sometimes we want to make sure that no further code can change an already assigned value of a variable. var or let can not restrict that. ES6 added the const keyword forthat purpose
Add the below line of code in the above file before the last line. and open in browser
const constVariable = 10; console.log(`initial value for constVariable = ${constVariable}`);constVariable = constVariable + 1; console.log(`final value for constVariable = ${constVariable}`);
2. Arrow functions (Expression Bodies)
Arrow functions aka Fat Arrow function, one of the most used features of ES6, are the victim of maybe the laziest naming, done in the history of JS. If you know java, JS Arrow functions ()=>{}are the same as Java lambdas()->{}but with an extra slash, thus called fat. (I guess).
Before 2016 in JS the reusable expressions used to be created as
var sum = function (a,b){ return a+b;};
But with ES6 Arrow functions you can write the same code as
let sum = (a,b)=> a+b;
NOTE: Arrow functions are not a direct replacement for function but only for a function expression. named function gets hoisted but function expression & arrow functions do not. So above two are not the same as the below code, because the below code can be used before it's declared
function sum(a,b) { return a+b;}
3. Default parameter
By design, all functions in javascript are variable args functions. what that means is that you can invoke a javascript function declared with n number of parameters by providing from 0to n number of arguments. The absent parameters variables get turned into zombies (undefined).
ES6, allows you to keep those zombies (undefined) out of scene, by assigning a default parameter value during function declarations. The default value is used only if the parameter is not passed.
// This is not the best method to sum a variable number of arguments // but it shows the power what defaults dofunction withDefaults(a=0, b=0,c=0){ return a+b+c;} function withoutDefaults(a,b,c){return a+b+c;}console.log('withDefaults ' + withDefaults(1,1)); console.log('withoutDefaults ' + withoutDefaults(1,1));
4. Template Literals — Interpolation
The ES6 does Intuitive expression interpolation for strings “if requested”.
And how do we request? By surrounding a string with a backtick. In that case,theJS engine uses the values of the variables inside the string, not the variables themself.
And how does it know what is a variable within a string? Anything mentioned within ${} is a variable. for example value of xxx will be used when mentioned as ${xxx}
const person = { name: 'MPS', age: ‘10’ } console.log(`${name} is ${age} year old`);
5. Enhanced Object Properties
Now you can create javascript Object without providing property names. See below.
const name = 'MPS', age = 10;const person = {name, age} console.log(`${person.name} is ${person.age} years old`)//This is same as ES5 below. const person2 = { "name": name, "age": age };
6. Destructuring Assignments
It's an expression that provides an Intuitive and flexible destructuring of Arrays or Objects into individual variables during the assignment.
It has the capability to match the variable names. Here is a simple example to create new constants from given object properties. As below.
const person = { name: 'MPS', age: ‘10' } const {name, age} = person; console.log(`name is ${name} and age is ${age}`); //Prints name is MPS and age is 10
You can also provide default values. When the given object doesn't have a property with same names the default values will be assigned. See below
const person = { name: 'MPS' } const {name, age='100'} = person; console.log(`name is ${name} and age is ${age}`); //Prints name is MPS and age is 100
The names do not have to be the same. you can destructure the a given object properties into constants with different name. In below example I’m creating a userName and userAge variable taking value from person object
const person = { name: 'MPS', age: ‘10' } const {name :userName,age :userAge} = person; console.log(`userName is ${userName} and userAge is ${userAge}`);
7. Promises
Promises deserve their own post. I’ll cover them in a separate article. For now, just for a quick overview, Java developers can treat ES6 Promises similar (not same) as the javaFuture.
As an oversimplification, consider it as a wrapper on top of an actual value which may be or may not be returned in a close or distant time in the future.
For example, if you invoke a function getItems() that uses an API to fetch the data from a server. Instead of waiting until the server returns a response, getItems()can right away return a Promise object. That promise will be fulfilled in the future and may or may not have the server response.
NOTE: I used words similar and oversimplifications above. Because unlike a true wrapper Promise does not hold the return value, instead it contains the execution logic that needs to be applied to the return value. We will discuss Promises in detail in a separate post.
8. keywords for clean Object-Oriented Programming
If you tried working on Object-oriented Javascript code before 2016, you might know the pain of overhandling the Prototypal Chain and the complexity of this. ES6 introduced class, extend, super, static, scoped let & const, and constructor()which help write clean & concise object-oriented UI code.
Below is some self-explanatory code to demostrate the use of keywords
<html><body>Check console logs</body> <script> window.onload = () => {class Vehicle {constructor(make) { this.make = make } start() { console.log(`${this.make} started`); } }class Car extends Vehicle {constructor(make, maxSpeed) { super(make); this.maxSpeed = maxSpeed; } go(){ super.start(); console.log(`We will drive at ${this.maxSpeed} speed`); } } new Car('toyota', 120).go(); } </script></html>
9. Modules
ES6 onwards, by default each “.js” file, is considered a Module.
The export/importkeywords can be used for exporting/importing values from/to modules without global namespace pollution & name collision. default keyword was also introduced to have one default export from a module & we can also import by wildcard ‘ *’ for a mass-mixin of values.
Lets have a file DoThings.js with following content
In the above case, when we import module Something it will represent the expression. You can import it and name it anything.
/** App.js ****/ import anyName from ’Something'
Conclusion
ES6 came with a lot of more features like Symbols, Map/Set, new built-in Methods for Array/String/Numbers, extended Regex support, and much more. But “in my opinion” the above 9 concepts are the prerequisite for every UI developer to start working on modern-day JS code.
More to come in this series in the next posts. Stay tuned.
Comments