ECMAScript6 the JavaScript with new wings

ECMAScript6 the JavaScript with new wings

ES6

ECMAScript 6 is the next generation of JavaScript, aka ES6 or Harmony which is a scripting language widely used for client side scripting on the web.

With its new promising objects enhancement and features ES6 makes JavaScript better for complex application, for libraries and also as a target of code generators. It helps programmer write less code and easily create complicated object.

ECMAScript6 adds many features that is taking language the next level and helping developer productivity and provide a more tenable code base.

ES6- the next version of JavaScript makes some things easier, it gives some great new language constructs that help to avoid some of the pitfalls. ECMAScript6 has many new crucial features that gives JavaScript Wings and brings the next evolution of JavaScript:

Daily basis features are:

Function Default:

>> ES6- the next version of JavaScript makes some things easier; it gives some great new language constructs that help to avoid some of the pitfalls.

>> It allows you to assign function parameter a default value if none is provided and with much less code:

Ex:

function sayMsg(msg='This is a default message') {
           console.log(msg);
      }

      sayMsg(); // This is a default message 
      sayMsg( 'This is a default message!'); // This is a default message!

 

SCOPE:

ES6 has introduced two new Keywords to declare a variable let and const that solve a common JavaScript difficulty:

  • let:

>> With ES6, you can simply declare the counter variable with let and will get expected result.

>> Variable declared using let will only be available in the current block instead of the entire function when using var.

>> While writing ES6 code, good ideas is to always use let instead of var.

Lets see how it behaves vs the var keyword:

function execute() {
  {
    console.log(hi); //error, the variable is not defined
    //code within curly braces is a "block"
    //this is only available within this block
    let hi = 1;
  }
  console.log(hi); //output: Error, hi is not defined
  for(let i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }
  console.log(i); //output: Error, i is not defined
}

Now we use var instead of let:

function execute() {
  {
    //with var, the variable declaration gets hoisted so we will not get an error
    //when attempting to use it before its declaration appears in code
    console.log(hi); //output: undefined
    var hi = 1;
  }
  console.log(hi); //output: 1
  for(var i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }
  console.log(i); //output: 10
}
  • Const:

>> The ability to create constant variables is something JavaScript was missing for a long time. With ES6 you’ll be able to create constants and make sure its value won’t be changed:

const param = 1;
            param = 2; //error: cannot change the value of a constant

>> When assigning an object, you will still be able to modify the it! :

const obj = { hello: 'world' };
            obj.hello = 'galaxy'; //no error!

>> But assigning another object, even if it has the same properties, will cause an error:

const obj = { hello: 'world' };
            obj = { hello: 'galaxy' }; //error

Iterating & destructuing:

ES6 is a succinct and flexible way to assign values from arrays or object into variables. And it makes easy to read, with two new language features:

  • Allows you to use the Spread Operator instead of argument object and give our list of arguments a more significant name:
function add(a,b) {
                return a+b;
            }
                 let nums = [5,4];
               console.log(add(...nums));
  • Allows you to use the for-ofloop to iterate over arrays and array-like objects.
for (let num of [1, 2, 3]) { 
              console.log(num);
            } 
             1 
             2 
             3

Arrow function:

>> ES6 introduces a shorter way of declaring a function using the arrow notation (=>). One of the reason ES6 introduces this way is functions are used alot in JavaScript from Node to AJAX callbacks to DOM event handlers.

 let square = num => num * num; 
  square(10) 
  100

Besides the new declaration style there are also some other differences such as;

  • If the function is a single statement and doesn’t have a body. This makes arrow function great to use with array methods.
[2, 3, 4].map(number => number + 2) // -> [ 4, 5, 6 ]
  • The this reference of an arrow function is always the same as its surrounding code. So you will not loose this in callbacks.

We often see something like this done in JS:

var self = this;
                    self.onclick = function() {
               self.doSomething();
              };

This pattern crops up occasionally. The solution is to use bind to fix this in the function. With arrows, we can instead just do this and it becomes very shorter using arrow function:

self.onclick = () => this.doSomething()

 

Other interesting features that may excite you:

Classes:

>> Here ES6 classes allow encapsulating and extending code.

>> They are syntactical sugar over the Objects and prototypes. They also offer a much nicer, clean and clearer syntax for creating objects. Several JavaScript libraries provide classes and inheritance.

Ex:

class Monster extends Character {
       constructor(x, y, name) {
              super(x, y);
              this.name = name;
              this.health_ = 100;
       }
        attack(character) {
              super.attack(character);
        }
        get isAlive() { return this.health > 0; }
        get health() { return this.health_; }

        set health(value) {
               if (value < 0) throw new Error('Health must be non-negative.');
               this.health_ = value;
               }
  }

Modules:

>> Provides a modular way of organizing and loading code.

>> If you don’t want to leave all of your JavaScript in just one file or you do want to re-use some functionality in other parts of your application, you’ll probably want to use modules. The magic keyword you need remember is export. Use export before the function you want to expose and you’re done.

Ex:

module Profile {
      // module code
      export var firstName = 'Akshay';
      export var lastName = 'Aman';
      export var year = 1973;
  }
  module ProfileView {
       import Profile.{firstName, lastName, year};

       function setHeader(element) {
            element.textContent = firstName + ' ' + lastName;
       }
         // rest of module
  }

Generators:

>> Specialized function and a better way to create iterations using function and the yeild keyword.

>> Each call to next() executes the function body till the next yield.

Ex:

function* range(start, end, step) {
       while (start < end) {
            yeild start;
            start += step;
         }
     }
    for (let i of  range(0, 10, 2))  {
  	console.log(i);
  }

 

Proxy:

>> Enables ES6 developers to represent virtualized objects.

Ex:

let target = {};
    let handler = {
          get(target, proKey, receiver) {
                 console.log('get' +propKey); 
                  return 123;     
          } 
    };
     let proxy = new Proxy(target, handler);

 

When we get the property proxy.foo, the handler intercepts that operation:

proxy.foo
      get foo
       123

 

Map:

>> Object that can be used to store key/value pairs. And your keys aren’t converted to strings implicitly.

Ex:

 var data = {val: "age"}; 
     var m = new Map([[name, "Akshay"], [data, 20]]); 
        m.get(name); 
   "Akshay" 
       m.get(data); 
  20

 

Rest Parameters:

>> Replaces the need for using arguments to access functions arguments. It allows you to get to an array representing “The rest of parameters”.

>> In the bellow example, as format takes two parameters, the first one is taken by str and the rest are put together into args as an array.

Ex:

function format (str, args) {
 return str.replace(/ \{\s*(\d+)\s*\}/g, function(m,n) {
    return args[n];
  });
}
  let msg = format (
       ' The  {0}st arg is a string, the  {1} are {2}.',
1,
   'rest' ,
    'unknown'
  );
 console.log(msg);

 

Set:

>> A collection object that can be used to store a list of data values.

>> Set of arbitrary values.

Ex:

var s = new Set([1, true, "three"]); 
s.has(true); 
true 
 s.has("true"); 
false 
 s.size();

 

Template string:

>> Clean way to build up string values.

>> In ES6, concatenating strings is simple with template strings.

Ex:

let first_name = "Akshay"
let last_name = "Singh"
let current_project = "xyy JavaScript school"

console.log(`My name is ${first_name} ${last_name} and I'm currently working on ${current_project}`);

 

Transpilers:

>> Transpilers in ES6 makes it possible to convert code from one syntax to another.

>> By integrating a transpiler into your development workflow you can write ES6 code that automatically gets converted into ES5 code using JavaScript task managers such as Grunt or Gulp.

>> To boost transpilers, ES6 allows to use language such as TypeScript to write ES6 code that gets converted into ES5.

>> TypeScript is superset of JavaScript that lets developer write “typed” ES6 code.