Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 3, 2021 05:40 pm GMT

Know all about ES6

ES6 also known as ECMAScript 6 is the latest JavaScript standard meant to ensure the interoperability of web pages across different web browsers.

Below mentioned are all the new concepts introduced in ES6 that you need to be aware of:

1) Block scoping

1.1) Let

function  fn  ()  {   let  x  =  0  if  (true)    {      let  x  =  1  //  only  inside  this  `if`   }}

1.2) Const

const  a  =  1

let is the new var. Constants work just like let ,but can't be reassigned.

2) Backtick strings

2.1) Interpolation

const  message  =  `Hello  ${name}`

2.2) Multiline strings

const  str  =  ` helloworld`

3) Binary and octal literals

let  bin  =  0b1010010 let  oct  =  0o755

4) New methods

4.1) New string methods

"hello".repeat(3) "hello".includes("ll") "hello".startsWith("he") "hello".padStart(8)   //  " hello""hello".padEnd(8)     //  "hello    ""hello".padEnd(8,  '!')  //  hello!!! "\u1E9B\u0323".normalize("NFC")

5) Classes

class  Circle  extends  Shape  {

5.1) Constructor

constructor  (radius)  {    this.radius  =  radius}

5.2) Methods

getArea  ()  {return  Math.PI  *  2  *  this.radius}

5.3) Calling superclass methods

expand (n) {    return  super.expand(n)  *  Math.PI}

5.4) Static methods

static  createFromDiameter(diameter)    {    return  new  Circle(diameter  /  2)  }}

6) Exponent operator

const  byte  =  2  **  8//  Same  as:  Math.pow(2,  8)

7) Promises

7.1) Making promises

new  Promise((resolve,  reject)  =>  { if  (ok)  {  resolve(result)  }  else  {  reject(error)  }})

Promises are used for asynchronous programming.

7.2) Using promises

promise.then((result)  =>  {    }).catch((error)  =>  {    })

7.3) Using promises with finally

promise.then((result)  =>  {    }).catch((error)  =>  {    }).finally(()  =>  {  //  logic  independent  of  success/error  })

The handler is called when the promise is fulfilled or rejected.

7.4) Promise functions

Promise.all() Promise.race()Promise.reject() Promise.resolve()

7.5) Async-await

async  function  run  ()  {const  user  =  await  getUser()const  tweets  =  await  getTweets(user)return  [user,  tweets]}

8) Destructuring

Destructuring assignment

8.1) Arrays

const  [first,  last]  =  ['Nikola',  'Tesla']

8.2) Objects

let  {title,  author}  =  { title:  'The  Silkworm', author:  'R. Galbraith'}

Supports for matching arrays and objects.

8.3) Default values

const  scores  =  [22,  33]const  [math  =  50,  sci  =  50,  arts  =  50]  =  scores//  Result://  math  ===  22,  sci  ===  33,  arts  ===  50

Default values can be assigned while destructuring arrays or objects.

8.4) Function arguments

function  greet({  name,  greeting  })  { console.log(`${greeting},  ${name}!`)}greet({  name:  'Gurshehzad Singh',  greeting:  'Hello!'  })

Destructuring of objects and arrays can also be done in function arguments.

8.5) Default values

function  greet({  name  =  'Gurshehzad Singh'  }  =  {})  { console.log(`Hi  ${name}!`);}greet()  //  Hi  Gurshehzad Singh!greet({  name:  'Rahul'  })  //  Hi  Rahul!

8.6) Reassigning keys

function  printCoordinates({  left:  x,  top:  y  }) { console.log(`x:  ${x},  y:  ${y}`)}printCoordinates({  left:  25,  top:  90  })

This example assigns x to the value of the left key.

8.7) Loops

for  (let  {title,  artist}  of  songs)  {}

The assignment expressions work in loops, too.

8.8) Object destructuring

const  {  id,  ...detail  }  =  song;

Extract some keys individually and remaining keys in the object using rest (...) operator.

9) Spread

9.1) Object spread

with Object spread

const  options  =  {...defaults, visible:  true}

without Object spread

const  options  =  Object.assign({},  defaults,{  visible:  true  })

The Object spread operator lets you build new objects from other objects.

9.2) Array spread

with Array spread

const  users  =  [...admins,...editors,'Gurshehzad Singh']

without Array spread

const  users  =  admins.concat(editors).concat([ 'Gurshehzad Singh' ])

The spread operator lets you build new arrays in the same way.

10) Functions

Function arguments

10.1) Default arguments

function  greet  (name  =  'Gurshehzad Singh')  { return  `Hello  ${name}`}

10.2) Rest arguments

function  fn(x,  ...y)  {//  y  is  an  Arrayreturn  x  *  y.length}

10.3) Spread

fn(...[1,  2,  3])//  same  as  fn(1,  2,  3)

Concepts included are: Default, rest, spread.

10.4) Fat arrows

setTimeout(()  =>  {})

10.5) With arguments

readFile('text.txt',  (err,  data)  =>  {...})

10.6) Implicit return

numbers.map(n  =>  n  *  2)//  No  curly  braces  =  implicit  return//  Same  as:  numbers.map(function  (n)  {  return  n  *  2  }) numbers.map(n  =>  ({result:  n  *  2}))//  Implicitly  returning  objects  requires  parentheses  around  the  object

Like functions but with this, it is preserved.

11) Objects

11.1) Shorthand syntax

module.exports  =  {  hello,  bye  }//  Same  as:  module.exports  =  {  hello:  hello,  bye:  bye  }

11.2) Methods

const  App  =  {  start  ()   {     console.log('running')  }}//  Same  as:  App  =  {  start:  function  ()  {}  }

11.3) Getters and setters

const  App  =  {   get  closed  ()  {      return  this.status  ===  'closed'    },   set  closed  (value)  {      this.status  =  value  ?  'closed'  :  'open'    }}

11.4) Computed property names

let  event  =  'click' let  handlers  =  {[`on${event}`]:  true}//  Same  as:  handlers  =  {  'onclick':  true  }

11.5) Extract values

const  fatherJS  =  {  age:  21,  name:  "Gurshehzad Singh"  }Object.values(fatherJS)//  [21,  "Gurshehzad Singh"] Object.entries(fatherJS)//  [["age",  21],  ["name",  "Gurshehzad Singh"]]

12) Modules

12.1) Imports

import  'helpers'//  aka:  require('')import  Express  from  'express'//  aka:  const  Express  =  require('').default  ||  require('')import  {  indent  }  from  'helpers'//  aka:  const  indent  =  require('').indentimport  *  as  Helpers  from  'helpers'//  aka:  const  Helpers  =  require('')import  {  indentSpaces  as  indent  }  from  'helpers'//  aka:  const  indent  =  require('').indentSpaces

import is the new require() .

12.2) Exports

export  default  function  ()  {    }//  aka:  module.exports.default  =  export  function  mymethod  ()  {    }//  aka:  module.exports.mymethod  =  export  const  pi  =  3.14159//  aka:  module.exports.pi  =  

export is the new module.exports .

13) Generators

13.1) Generators

function*  idMaker  ()  { let  id  =  0while  (true)  {  yield  id++  }}let  gen  =  idMaker() gen.next().value  //    0 gen.next().value    //    1 gen.next().value //    2

13.2) For..of iteration

for  (let  i  of  iterable)  {}

For iterating through generators and arrays.

These are all the latest modifications made in ES6 in order to improve its efficiency is JS and Development world.

Thanks for reading!


Original Link: https://dev.to/gurshehzadsingh/know-all-about-es6-3fho

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To