ES6 Features

Today, I’m going to write a post on ECMAScript 6 major feature. In addition, I will provide a working example of each feature.


Variables defined using const cannot be changed.

const pi = 3.14;
pi = 4.2;

Uncaught TypeError: Assignment to a constant variable.
at <anonymous>:2:4


Till ES5 we have only global and function scope. However, ECMAScript 6 introduced a block level scope called ‘let’.

Example with var

function sampleDemo() {
 var i = 20;
 for(var i=0;i<10;i++){
 console.log(i) // output 10; 

Example with ‘let’

function sampleDemo() {
 let i = 20;
 for(let i=0;i<10;i++){
 console.log(i) // output 20; 

Arrow functions

Arrow functions are similar to normal functions. But, more expressive closure syntax.

let wish = (name) => {
wish('commandsTech'); // output: Hello commandsTech

Template strings

Template strings help in the more clean way of writing long strings.


  • Array destructuring
    let stack = ['Angular', 'React', 'vue'];
    let [stack1, stack2, stack3 ] = stack;
    console.log(stack1); // output Angular
    console.log(stack2); // output React
    console.log(stack3); // output vue
  • Object destructuring
    let profile = {
    name : 'commandsTech',
    location : 'Hyd'

    Before ES6 if you want to extract out variables

    let profileName =;
    let profileLocation = profile.location;

    Object destructuring helped us to do the achieve the same in just one line

    let { name: profileName , location: profileLocation } = profile;
    console.log(profileName); // ouput : commandsTech
    console.log(profileLocation); // output: Hyd
  • function destructuring
    Function destructuring simply the way in which parameters are passed. In addition, we can also pass default values for parameters.

    function sum({num1,num2,num3, num4=50}) {
  • for-of loop

In for-each and for-in ‘continue’ ‘break’ and ‘return’ cannot be used so ES6 bought for-of loop.

var UIStack = ['Angular', 'react', 'vue', 'd3'];
for(technology of UIStack){
Output: Angular react vue d3


ECMAScript 6 that help us in importing and exporting modules. As a result,  we can use the function of one module in another module.
As shown in the below sample code methods or variables from one module can be imported into another.

// math.js
export pi = 3.17;
export sum = function (a,b) { return a+b;}

// sample.js
Import { pi, sum} from ‘/math.js’;


prior to ES6, the only way to store key and values is the object. ECMAScript 6 introduces a data structure called maps to store key-value pairs. The map provides a set method to pass data, get to retrieve, size to get map size, delete to remove a property, keys method to retrieve all keys and values to retrieve all values present in the map.

let scores = new Map([["dravid",50]]);


console.log(scores.get('kohli')); // output 100;
console.log(scores.size);  // output 4
console.log(scores.has('sehwag')); // output true
console.log(scores.keys()); // output all keys
console.log(scores.values()); // output all values


Similar to Map set is also a data structure but the set can store only values that are unique. Likewise sets also provide add, size, has and clear methods.

let scores = new Set();


console.log(scores); // output {"sachin", "sehwag", "kohli", "raina"}
console.log(scores.size); // output 4
console.log(scores.has('sachin')); // true


Promise is introduced as part of ES6. Promise represents a value which may be available now, future or never. Above all Promise object is used for asynchronous operations, prior to promise call back are used to handle asynchronous operations

a promise can be in one of these states

  •  fulfilled
  • pending
  • rejected
    Promise methods
    All method is for handling multiple promises.

    var p1 = Promise.resolve(3);
    var p2 = 1337;
    var p3 = new Promise((resolve, reject) => {
      setTimeout(resolve, 100, 'foo');
    Promise.all([p1, p2, p3]).then(values => { 
      console.log(values); // [3, 1337, "foo"] 

    Catch method to handle promise rejection

    p.catch(function(reason) {
       // rejection

    then method on promise takes two functions as parameters.  first will be a success call back and second is a failure callback.

    p.then(function(value) {
       // fulfillment
      }, function(reason) {
      // rejection

    race handles multiple promises but returns the promise that gets first resolve or reject.

    Promise.race([p1, p2]).then(function(value) {
    // Both resolve, but if p2 is faster then p2 output is executed

    Reject method returns a promise with a reason of rejected object.

    Promise.reject(new Error('fail')).then(function(error) {
      // not called
    }, function(error) {

    Resolve method returns a promise object with resolved value.

    Promise.resolve('Success').then(function(value) {
      console.log(value); // "Success"
    }, function(value) {
      // not called

Classes & Inheritance

Classes introduced in ECMAScript simplified the creation of classes.

class Person {
 constructor(name,age){ = name;
  this.age = age;  
 hello () {
   console.log('Hey',, this.age);

var p1 = new Person('vijay',25);


Just like inheritance in java programming properties, and method of a class can be inherited to another using extends keyword.

class Animal{
constructor() {}
eat () {
console.log('Animal can eat');

class Lion extends Animal {
constructor() {
super(); = 'Lion King';
who() {
console.log('Hey Im',;

let t1 = new Lion();
console.log(t1); // Tiger
console.log(t1.who()); // Hey Im Lion King
console.log(; // Animal can eat

ES5 Features

Major features introduced in ECMAScript 5

    1. It’s okay to have trailing commas in object literals. Since beginning javascript allowed trailing commas in the array.
      var obj = { 'name': 'Commands Tech', 'category': 'tech new', }

      However, using trailing commas in JSON is invalid and throws the error.

      var myJSON = '{"name":"CommandsTech", "city":"New York",}';
      VM793:1 Uncaught SyntaxError: Unexpected token } in JSON at position 42
      at JSON.parse (<anonymous>)
      at <anonymous>:2:6
    2. No reserved keywords for variable names.  Reserved keywords should not be used as variable names. Example:
      var NaN = 'CommandsTech';
      console.log(NaN); // NaN
    3. parseInt() defaults to radix 10

    4. JSON.parse() & JSON.stringify()

      JSON.parse(): To convert text into a javascript object
      JSON.stringify(): To convert a javascript object into string

    5. bind()

      Description:  Bind method allows us to call a function with this set explicit. bind method returns a bounded function with the bound object.

      this.x = 10;
      var moduleX = {
      	x : 20,
      	getX: function() { return this.x; }
      var retriveX = moduleX.getX;
      var getBoundX = retriveX.bind(moduleX);
      Output: 20
    6. trim()

      Description: Removes whitespace on both ends of the string and returns a string

      var name = ' commandsTech ';
    7.  every()

      Description: method takes a function as input parameter and checks if each element in an array passes the test and return a boolean

      var bills = [132, 233, 916, 140];
      function checkBills(bill) {
      return bill >= 100;
      bills.every(checkBills); // Output true
    8.  filter()

      Description:  method creates a new array with all elements that pass a test implemented by the provided function

    9. map()

      Description:  method creates a new array with the result of calling a provided function on each element. 

  1. forEach()

    Description: method calling a provided function on every array element.

  2. reduce()

    Description: reduce method results in a single value that is a result of calling a reducer function on each element.
    filter, map, forEach, map method examples


    Description:  returns the current time

  4. Date.prototype.toISOString

  5. new Date(string) and Date.parse(string)

  6. Object.keys()

    Description: Fetch all the keys() present in an object. Object.keys() method returns an array of own properties

    const profile = {
    name: 'commandsTech',
    location: 'Hyd',
    console.log(Object.keys(profile)); // ['nane','location']
  7. Object.create()
    Description: Create a new object taking the existing object’s prototype

    var profile = {
    name: 'commandsTech'
    var profile2 = Object.create(profile);; // output: "commandsTech"
  8. Object.defineProperty & Object.defineProperties
    Description: Using defineProperties we can modify or define properties on an object.

    const profile = {};
    Object.defineProperties(profile, {
    name: {
    value: 'commandsTech',
    writable: true
    // expected output: commandsTech
  9. Object.getOwnPropertyDescriptor()

    Descriptor: Using this method we can know the description of the property specified within the object

    var profile = {
    location: "hyd"
    var descriptor = Object.getOwnPropertyDescriptor(profile, 'name');
    console.log(descriptor.configurable); // output: true
  10. Object.getOwnPropertyNames(obj)

    Description: All the properties present on an object are returned

    var profile = {
    location: "hyd"
    Object.getOwnPropertyNames(profile); // output ['name', 'location']
  11. Object.seal()

    Description: the seal on object prevents adding of new properties and marks all existing as non-configurable properties. Values of a property can be changed(if writable).
    const profile = {
    name: 'commandsTech'
  12. Object.freeze()

    Description: Object that is frozen cannot be changed. The freeze prevents adding new property & deleting the existing property. Prevents changing the enumerability, configurability or writability or changing. Changing of the prototype is also prevented on the frozen object.

    const profile = {
    name: 'commandsTech'
  13. Object.isSealed()

    Description: Checks if an object is sealed or not

    const profile = {
    name: 'commandsTech'
    console.log(Object.isSealed(profile)); //output: false
    console.log(Object.isSealed(profile)); // output: true
  14. Object.isFrozen()
    Description: Checks if an object is frozen or not

    const profile = {
    name: 'commandsTech'
    console.log(Object.isFrozen(profile)); //output: false
    console.log(Object.isFrozen(profile)); // output: true
  15.  Property Attributes: writeable, value, enumerable, configurable, get, set.
  16. ‘use strict’;

    Description: Use strict indicates that javascript code should be executed in “strict mode”.

    Example with use strict

    "use strict";
    name = 'commandsTech'; // This will throws an error (name is not defined).

    Example without use strict

    name = 'commandsTech'; // This will not throw an error even though name is not defined

Javascript interview questions

Some of the javascript interview questions and topics for UI Developers.

Javascript Interview questions

  1. What is Javascript?
  2. Ways to Handle Javascript Event handlers?
  3. Hoisting Variables and function
  4. What is event Bubbling and capturing?
  5. Javascript pass by value or pass by reference
  6. Javascript functions 
  7. Variables scope
  8. Dom selectors
  9. Ways to create object and arrays
  10. Ways to loop in javascript
  11. Javascript types
  12. what is hapOwnProperty? when it’s useful?
  13. String, Array, Number methods
  14. What is a closure?
  15. How to achieve inheritance?
  16. Javascript encapsulation
  17. Explain call, apply, bind
  18. Javascript Event loop
  19. Callback functions
  20. Javascript promises
  21. Configuring objects
  22. Javascript design patterns
  23. Polyfills
  24. Associative arrays
  25. Freeze, Seal
  26. ES5 Features
  27. ES6 Features
  28. ES7 Features
  29. When to use map, reduce and filter methods?
  30. Explain javascript ‘this’

React fundamentals

With performance and lite weight Reactjs is able to pull many frontend developers to go with this library. Even Google and job trends show Reactjs library is on the boom and overtaking the other frameworks and libraries.

React core concepts that help you to kick-start building the Reactjs application.

  • Stateless & Stateful Components
  • State
  • Props
  • Routing

1. Stateless & Stateful Components

Stateless components are functional components only receives the props that are received from a parent and returns the element.  In addition, Stateless components cannot change the component state’s as well as they don’t have control over the methods of React’s life cycle.

Sample stateless component

import React from 'react';

const Intro = props => (
<p className="App-intro"> {props.message} </p> 

export default Intro;

Stateful components are class components having access to the lifecycle of the component.

Sample stateful component:

import React, { Component } from 'react';
import './App.css';
import Intro from '../Intro';
import Main from '../Main';

class App extends Component {

render() {
 return (

  <div className="App">
   <header className="App-header">
   <h1 className="App-title">Web Series List</h1>
   <Main />

export default App;

2. State

State holds the information that helps in managing the components internal state that affects the rendered output.  In the below example we are using a setState method to update the state of our component on change of search text.

import React, { Component } from 'react';
import 'whatwg-fetch';
import SeriesList from '../../components/SeriesList';
import Intro from '../../components/Intro';

class Series extends Component {

  state = {
   series: [],
   seriesName: '',
   isFetching: false

  onSeriesInputChange = (e) => {
    this.setState({seriesName:, isFetching: true});
    .then(response => response.json())
    .then(json => this.setState({series: json, isFetching: false}));

render() {
  return (
     <Intro message="Welcome to web series" />
      Total: {this.state.series.length}
    <input type="text" onChange={this.onSeriesInputChange} placeholder="Search web series" />
     this.state.series.length ===0 &&
     this.state.seriesName.trim() === '' && 
     !this.state.isFetching && <p>No results found</p>
     this.state.isFetching && <p>Loading...</p> 
    <SeriesList list={this.state.series} /> 

export default Series;

3. Props

Similar to sate props also hold information but this information is passed to the child component from its parent as props. Props nothing but properties. For example below we are passing the message as a prop to the Intro component from its parent.

 <Intro message="Welcome to web series" />
import React from 'react';

const Intro = props => (
<p className="App-intro"> {props.message} </p> 

export default Intro;

4. Routing

‘react-router-dom’ is a library built on top of React that helps in achieving routing functionality in react applications. You can install it using npm command ‘npm install react-router-dom’.

Imported BrowserRouter from the library and place the main app component inside it.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter} from 'react-router-dom';


Component route details placed inside the switch component.

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import About from '../About';

const Main = (props) => (
<Route exact path="/about" component= {About} />

export default Main;

Prerequisites: HTML, CSS & Javascript are the technologies once should know to build or learn a react app.

Data visualization using D3js

  • What? D3 is a javascript library for creating interactive, dynamic data visualizations in the browser.
  • How? D3 Uses digital data to drive the formation, control and graphical presentation. D3 stands for Data Driven Document.
  • Why? D3 is an open source, an extremely helpful in viewing huge data & data visualization is the best way to understand, represent & analyze.

Let’s create a simple bubble chart with d3.

1. Get the dataset that you like to visualize

 // dataset
var dataset = [
[15, 120], [480, 90], [1250, 50], [1100, 33], [1330, 915],
[4110, 112], [4715, 414], [215, 617], [815, 21], [2120, 818],
[6010, 1510]

2. Define dimensions of the chart ie. heigh, width and padding

//Defining Width, height and padding
var w = 600;
var h = 350;
var padding = 70;

3. Create x-scale

 var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[0]; })])
.range([padding, w - padding * 2]);

4. Create y-scale

 var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[1]; })])
.range([h - padding, padding]);

d3 provides different scales depending on the type of input data set we choose the appropriate suitable scale, here we are using a linear scale. the domain is the input values and range is nothing but the output element.

5. Define x-axis

 // define xAxis
var xAxis = d3.svg.axis()

6. Define y-axis

 // define yAxis
var yAxis = d3.svg.axis()

We use d3 axis method to define an axis. To scale the method we need to pass the scales that we created initially. Orient method is to specify the position of the axis.

7. Create SVG

 // create svg
var svg ="body")
.attr("width", w)
.attr("height", h);

appending chart to the body tag, you can use a tag of your choice.

8. Create circles/bubbles

 //Create circles
.attr("cx", function (d) { return xScale(d[0]) })
.attr("cy", function (d) { return yScale(d[1]) })
.attr("r", 10)
.attr("fill", 'cornflowerblue')

enter method creates the initial data to elements. creating a circle element for each data element in the array. cx, cy and are circles x position, y position, and radius.

9. Create x-axis

//create xAxis
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")

10. Create y-axis

 //create yAxis
.attr("class", "axis")
.attr("transform", "translate(" + padding + ", 0)")

transform attribute is the and call method to create y-axis.

You can find the above code working demo and some additional charts to learn here

The main advantage of d3js over other libraries is we have full control over the chart, that helps us in creating custom charts.

Javascript functions

Javascript functions are defined using the function keyword. All the functions in javascript are objects or reference types, that can be assigned to a variable or passed as a parameter function.

Function Declaration

Functions can be declared in different ways

  1. Declaration way
    function keyword followed by the function name

    function greeting(name) {
       return 'Hello '+name;
    Output: 'Hello Messi'
  2. Expression way
    In the expression, way function doesn’t have a name and we assign the function to a variable. Functions that are declared without any name are called anonymous functions.

    var greeting = function (name) {
       return 'Hello '+name;
    Output: 'Hello Messi'
  3. Function constructor
    Javascript provides a built-in function constructor called Function() through which a function can be defined.
var greeting  = new Function ("name", "return 'Hello ' + name ");

Function Hoisting

In javascript, hoisting is a mechanism in which javascript engine will push the function declarations on to the top.  Therefore we can invoke a function even before we declare and it works without any error.

Note: Function hoisting works only for declaration way and in expression way js throws an error.

Hoisting declaration way

Hoisting expression way

Function as parameter

A function can be passed as a parameter to another function. In below syntax, we are passing an anonymous function as a parameter to the Array sort function.

var bills = [40,50,10,60,70,30,50];

bills.sort(function(number1, number2){
return number1 - number2;
Output: [10, 30, 40, 50, 50, 60, 70]

Function invocation 

Function invoke is nothing but calling a function.

    1. Invoking function as a function
      function greeting(name) {
      return 'Hello '+name;
    2. Invoking function as a method.
      var student = {
      name : 'vijay',
      location: 'Hyderabad',
      getDetails: function () { return + this.location }
      output: "vijayHyderabad"

      In the above syntax, this refers to the current object.

    3. Immediately-invoked functions
      Immediately-invoked function expression (IIFE) also known as self-invoking anonymous functions. Generally, functions need explicit invoke or call but Immediately invoked function expression (IIFE) functions are executed right after defining the function.

      (function() {
        console.log('Hello world');
      output: 'Hello world';

      These functions have their own scope and prevent global namespace pollution.

  1. call
    A call allows us to specify this explicitly and invoke the function with the list of arguments. The calls were introduced in ECMAScript 3.

    function add(c){
    return console.log(this.a+this.b+c);
    var obj = {
    a : 1,
    b : 2
    Output: 6
  2. apply
    apply method allows us to specify this explicitly and invoke the function with a single array of arguments. apply method was introduced in ECMAScript 3.

    var arr = [1,2,3,5,67,8];
    var max = Math.max.apply(null,arr);
    Output: 67
  3. bind came in ECMAScript 5. Bind method allows us to call a function with this set explicit. bind method returns a bounded function with the bound object.
this.x = 10;
var moduleX = {
	x : 20,
	getX: function() { return this.x; }
var retriveX = moduleX.getX;
var getBoundX = retriveX.bind(moduleX);
Output: 20


(adsbygoogle = window.adsbygoogle || []).push({});

Smart way of looping in JavaScript

Whenever there is a scenario of looping the first thing that strikes our mind is for. But actually, there are clean and better ways to loop without using for in javascript.


ECMAScript 5 provided methods forEach, map, reduce, filter and ECMAScript 6 provided find method that resides on Array prototype. Therefore depending on the scenario, we can use appropriate methods instead of for loop.

    • forEach: forEach() method calling a provided function on every array element.
      • Demo Array.forEach forEach
    • map: map() method creates a new array with the result of calling a provided function on each element. 
      • Demo map


  • reduce: reduce() method results a single value that is a result of calling a reducer function on each element.
    • Demo Array.reduce()js reducer method
  • filter: filter() method creates a new array with all elements that pass a test implemented by the provided function
    • Demo Array.filter()filter method
  • find: method returns the value of the first element in an array that passes a test implemented by the provided function
    • Demo Array.find()

Who is better at performance?

Obviously for loops are faster than Javascript methods(map, reduce, filter, find)  because these methods can have extra overhead, behind the scene even these methods could be using for loop.

Demo reducer vs forfor vs reduce

If for loops are faster then why javascript methods?

These methods are self-explanatory and using the appropriate method for the use case can help the team understand what you are doing.