Know all about ES6

gurshehzadsingh

Gurshehzad Singh

Posted on May 3, 2021

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`
   }
}
Enter fullscreen mode Exit fullscreen mode

1.2) Const

const  a  =  1
Enter fullscreen mode Exit fullscreen mode

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}`
Enter fullscreen mode Exit fullscreen mode

2.2) Multiline strings

const  str  =  ` 
hello
world
`
Enter fullscreen mode Exit fullscreen mode

3) Binary and octal literals

let  bin  =  0b1010010 
let  oct  =  0o755
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

5) Classes

class  Circle  extends  Shape  {
Enter fullscreen mode Exit fullscreen mode

5.1) Constructor

constructor  (radius)  
{ 
   this.radius  =  radius
}
Enter fullscreen mode Exit fullscreen mode

5.2) Methods

getArea  ()  {
return  Math.PI  *  2  *  this.radius
}
Enter fullscreen mode Exit fullscreen mode

5.3) Calling superclass methods

expand (n) {
    return  super.expand(n)  *  Math.PI
}
Enter fullscreen mode Exit fullscreen mode

5.4) Static methods

static  createFromDiameter(diameter)  
  { 
   return  new  Circle(diameter  /  2)
  }
}
Enter fullscreen mode Exit fullscreen mode

6) Exponent operator

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

7) Promises

7.1) Making promises

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

Promises are used for asynchronous programming.

7.2) Using promises

promise
.then((result)  =>  {  ···  })
.catch((error)  =>  {  ···  })
Enter fullscreen mode Exit fullscreen mode

7.3) Using promises with finally

promise
.then((result)  =>  {  ···  })
.catch((error)  =>  {  ···  })
.finally(()  =>  {  //  logic  independent  of  success/error  })
Enter fullscreen mode Exit fullscreen mode

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

7.4) Promise functions

Promise.all(···) 
Promise.race(···)
Promise.reject(···) 
Promise.resolve(···)
Enter fullscreen mode Exit fullscreen mode

7.5) Async-await

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

8) Destructuring

Destructuring assignment

8.1) Arrays

const  [first,  last]  =  ['Nikola',  'Tesla']
Enter fullscreen mode Exit fullscreen mode

8.2) Objects

let  {title,  author}  =  { title:  'The  Silkworm', author:  'R. 
Galbraith'
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!'  })
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

8.6) Reassigning keys

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

printCoordinates({  left:  25,  top:  90  })
Enter fullscreen mode Exit fullscreen mode

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

8.7) Loops

for  (let  {title,  artist}  of  songs)  {
···
}
Enter fullscreen mode Exit fullscreen mode

The assignment expressions work in loops, too.

8.8) Object destructuring

const  {  id,  ...detail  }  =  song;
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

without Object spread

const  options  =  Object.assign(
{},  defaults,
{  visible:  true  })
Enter fullscreen mode Exit fullscreen mode

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'
]
Enter fullscreen mode Exit fullscreen mode

without Array spread

const  users  =  admins
.concat(editors)
.concat([ 'Gurshehzad Singh' ])
Enter fullscreen mode Exit fullscreen mode

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}`
}
Enter fullscreen mode Exit fullscreen mode

10.2) Rest arguments

function  fn(x,  ...y)  {
//  y  is  an  Array
return  x  *  y.length
}
Enter fullscreen mode Exit fullscreen mode

10.3) Spread

fn(...[1,  2,  3])
//  same  as  fn(1,  2,  3)
Enter fullscreen mode Exit fullscreen mode

Concepts included are: Default, rest, spread.

10.4) Fat arrows

setTimeout(()  =>  {
···
})
Enter fullscreen mode Exit fullscreen mode

10.5) With arguments

readFile('text.txt',  (err,  data)  =>  {
...
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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  }
Enter fullscreen mode Exit fullscreen mode

11.2) Methods

const  App  =  { 
 start  () 
  {
     console.log('running')
  }
}
//  Same  as:  App  =  {  start:  function  ()  {···}  }
Enter fullscreen mode Exit fullscreen mode

11.3) Getters and setters

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

11.4) Computed property names

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

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"]]
Enter fullscreen mode Exit fullscreen mode

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('···').indent


import  *  as  Helpers  from  'helpers'
//  aka:  const  Helpers  =  require('···')


import  {  indentSpaces  as  indent  }  from  'helpers'
//  aka:  const  indent  =  require('···').indentSpaces
Enter fullscreen mode Exit fullscreen mode

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  =  ···
Enter fullscreen mode Exit fullscreen mode

export is the new module.exports .

13) Generators

13.1) Generators

function*  idMaker  ()  { let  id  =  0
while  (true)  {  yield  id++  }
}


let  gen  =  idMaker() gen.next().value  //  →  0 gen.next().value    //  →  1 gen.next().value //  →  2
Enter fullscreen mode Exit fullscreen mode

13.2) For..of iteration

for  (let  i  of  iterable)  {
···
}
Enter fullscreen mode Exit fullscreen mode

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!

💖 💪 🙅 🚩
gurshehzadsingh
Gurshehzad Singh

Posted on May 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Features of Javascript You Should Know
javascript Features of Javascript You Should Know

October 17, 2024

Building 100% reusable UI kits
javascript Building 100% reusable UI kits

July 8, 2024

Splitting and Caching React Chunks
javascript Splitting and Caching React Chunks

December 30, 2023