Tag Archives: ES6

ES6 Basics

JavaScript Basics

1. Const : We cannot reset the value of constant variable.

const value = true;

2. let : with let keyword, we can limit the scope of a variable to any code block.

let topic = true;

3. Template String: with template string, we can create one string and insert the variable values by surrounding them with ${}

`${Salutation} ${firstName} ${lastName}`

4. Default Parameters: If a value is not provided for the argument, default value will be used. default argument can be any type.

function activity(name="Test"){
 console.log(`${name}`);
 }

5. Arrow Function: With arrow functions, you can create the functions without using the function keyword.

var showName = (firstName,lastName) =>`${firstName} ${lastName}` 
var displayRole = role => {
if(!role){
  throw new Error('Role is required');
}
return `${role}` 
}

Note: Arrow function protect the scope of this, but not block the scope of this.

6. Transpiling ES6: Not all browser supporting ES6, so we need to convert it to ES5 code before running it in browser.One of the popular tool for transpiling  is Babel.You can transpile the javascript directly in the browser using inline Babel transpiler. You just include the browser.js file and any script with type=”text/babel” will be converted.

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"> </script>
<script src="script.js" type="text/babel"></script>

Note: Transpiling approach is not a good idea for production because it will slow down the application.

ES6 Objects and Arrays:

1. Destructuring Assignment:

It allows us to locally scope fields within an object and to declare which values will be used.

  • Destructuring object having four keys and we only want to use two keys out of them.
 
var object= { salutation: "Mr.",
 firstName: "Test",
 lastName: "Data",
 role: "Developer"}

var {firstName,lastName} = object console.log(firstName,lastName); 
  • Destructuring incoming function argument:
var name = { firstName: "Test",
lastName: "Data" }

var showFirstName = ({firstName}) => console.log(`${firstName}`)
showFirstName(name)
  • Assign the specific element value of an array to a variable name:
var [salutation] = ["Salutation","FirstName","LastName"]
console.log(salutation) //Salutation
var [,,lastName] = ["Salutation","FirstName","LastName"]
console.log(lastName) //LastName 

2. Object Literal Enhancement:

It the process of restructuring or putting back together.

  • with object literal enhancement, we can grab variables from global scope and turn them into an object.
var firstName = "Test"
var lastName = "Data"
var name = {firstName,lastName}
console.log(name) // {firstName:"Test", lastName:"Data"} 
  • with object literal enhancement, we can create object method.
var print = () =>{ console.log(`${this.firstName} ${this.lastName}`)}
var name = {firstName, lastName, print}
name.print() // Test Data 
  • while defining object methods, it is no longer necessary to use the function keyword
const newName = { firstName,
lastName,
print(){
console.log(`${this.firstName} ${this.lastName}`);
},
printWithSalutation(salutation){
 console.log(`salutation ${this.firstName} ${this.lastName}`);}
}

3. The Spread Operator:

It represents with three dots(…) that performs several different tasks.

  • With Spread Operator, we can combine the contents of arrays.
 var fruits = ["Mango","Grapes","Banana"]
 var drinks = ["Mazza","Rani","Tropicana"]
 var fruitDrink = [...fruits,...drinks] 
 console.log(fruitDrink.join(",")) //Mango,Grapes,Banana,Mazza,Rani,Tropicana
 

Note: Spread Operator creates the copy of the array and then do the specified process.

  • Spread Operator can be used to get some, or the rest, of the items in the array
 var [first,...rest] = fruits
 console.log(rest.join(",")) //Grapes,Banana
 
  • Spread Operator can also be used to collect function arguments as an array.
function directions(...args){ 
var [start, ...remaining] = args
 var [finish, ...stops] = remaining.reverse()
 console.log(`drive through ${args.length} towns`)
 console.log(`start in ${start}`)
 console.log(`the destination is ${finish}`)
 console.log(`stopping ${stops.length} times in between.`) 
}
 directions("Hapur","Ghaziabad","Noida","Gurgaon")
  • Spread Operator can also be used for Objects.
var employee = { name: "Test", age: "20" }
var department = " Admin"
var company = { ...employee, department }
console.log(company) // { name:"Test", age:"20", department:"Admin" }

Promises:

It give us a way to make sense out of asynchronous behavior. It simplify back to a simple pass or fail.

Classes:

ES6 introduces class declaration, but javascript still works the same way. Functions are objects and inheritance is handled through the prototype.

class Person
{ 
constructor(name,age){
 this.name = name this.age = age
 }
 display(){
 console.log('My name is ${this.name} and I am ${this.age} years old.') }
}

Note: All types should be capitalized, due to that we will capitalize all class names.

  • We can create the new instance of the class using new keyword.
const personObj = new Person("Test data", 30);
 console.log(personObj.display()); //My name is Test data and I am 30 years old.

Simple Inheritance:

class UID extends Person{
 constructor(name, age, uniqueID){
 super(name,age)
 this.uniqueID = uniqueID 
}
 print(){
 super.print()
 console.log('And ${this.uniqueID} is my uniqueID.') }
 }

const personDtl = new UID("Test Data", 30, 1234567)
 console.log(personDtl.print()); //My name is Test data and I am 30 years old. And 1234567 is my uniqueID.

ES6 Modules:

JavaScript module is a piece of reusable code that can easily be incorporated into other javascript files.JavaScript module stored in separate file, one file per module.

  • Export multiple javascript object per module.
(script1.js)

export const display(name) => log(name, new Date())
export const log(name, timestamp) =>
console.log(`${timestamp.toString()} : ${name}`)
  • export default, using this we can export single javascript object from a module.
(script2.js)
const person = new Person("Test data", 26)
export default person
  • Modules can be consumed in other javascript file using import statement. Modules containing multiple export can take advantage of object destructuring.
import {display, log} from './script1'
import person from './script2'

display("display Test data details")
log("logging test data details")

person.print()
  • we can scope modules variables locally under different variable names.

import {display as d, log as l} from './script1'

p("display test data details")  l("logging test data details")

  • we can import everything into single  variable using *.

import * as prsn from './script'

CommonJS:

It is the module pattern that is supported by all versions of Node.js

  • with commonJS, object are exported using module.exports
module.exports = {display, log}
  • with commonJS, objects are imported using require function

const {display, log} = require('./script1')