Know all about ES6
Tags: javascript, webdev, react, programming
Published: 2021-05-03 17:40:43

***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**
```js
function  fn  ()  
{ 
  let  x  =  0
  if  (true) 
   {
      let  x  =  1  //  only  inside  this  `if`
   }
}
```

 **1.2) Const**
```javascript 
const  a  =  1
```

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

***2) Backtick strings***

 **2.1) Interpolation**
```javascript
const  message  =  `Hello  ${name}`
```

 **2.2) Multiline strings**
```javascript
const  str  =  ` 
hello
world
`
```

***3) Binary and octal literals***
```js
let  bin  =  0b1010010 
let  oct  =  0o755
```

***4) New methods***

 **4.1) New string methods**

```js
"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***
```js
class  Circle  extends  Shape  {
```

 **5.1) Constructor**
```js
constructor  (radius)  
{ 
   this.radius  =  radius
}
```


 **5.2) Methods**
```js
getArea  ()  {
return  Math.PI  *  2  *  this.radius
}
```
 **5.3) Calling superclass methods**
```js
expand (n) {
    return  super.expand(n)  *  Math.PI
}
```



 **5.4) Static methods**
```js
static  createFromDiameter(diameter)  
  { 
   return  new  Circle(diameter  /  2)
  }
}
```
***6) Exponent operator***

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

***7) Promises***

 **7.1) Making promises**
```js
new  Promise((resolve,  reject)  =>  
{ if  (ok)  {  resolve(result)  }  
else  {  reject(error)  }
})
```

Promises are used for asynchronous programming.

 **7.2) Using promises**
```js
promise
.then((result)  =>  {  ···  })
.catch((error)  =>  {  ···  })
```
 **7.3) Using promises with finally**
```js
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**
```js
Promise.all(···) 
Promise.race(···)
Promise.reject(···) 
Promise.resolve(···)
```

 **7.5) Async-await**
```js
async  function  run  ()  {
const  user  =  await  getUser()
const  tweets  =  await  getTweets(user)
return  [user,  tweets]
}
```
***8) Destructuring***

*Destructuring assignment*

 **8.1) Arrays**
```js
const  [first,  last]  =  ['Nikola',  'Tesla']
```


 **8.2) Objects**
```js
let  {title,  author}  =  { title:  'The  Silkworm', author:  'R. 
Galbraith'
}
```

Supports for matching arrays and objects.

 **8.3) Default values**
```js
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**
```js
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**
```js
function  greet({  name  =  'Gurshehzad Singh'  }  =  {}) 
 { console.log(`Hi  ${name}!`);
}


greet()  //  Hi  Gurshehzad Singh!
greet({  name:  'Rahul'  })  //  Hi  Rahul!
```


 **8.6) Reassigning keys**
```js
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**
```js 
for  (let  {title,  artist}  of  songs)  {
···
}
```

The assignment expressions work in loops, too.

 **8.8) Object destructuring**
```js
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*
```js
const  options  =  {
...defaults, visible:  true
}
```

  *without Object spread*
```js
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*

```js
const  users  =  [
...admins,
...editors,
'Gurshehzad Singh'
]
```
  *without Array spread*
```js
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**

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

 **10.2) Rest arguments**
```js
function  fn(x,  ...y)  {
//  y  is  an  Array
return  x  *  y.length
}
```


 **10.3) Spread**
```js
fn(...[1,  2,  3])
//  same  as  fn(1,  2,  3)
```

Concepts included are: Default, rest, spread.

 **10.4) Fat arrows**

```js
setTimeout(()  =>  {
···
})
```

 **10.5) With arguments**
```js
readFile('text.txt',  (err,  data)  =>  {
...
})
```

 **10.6) Implicit return**
```js
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**
```js
module.exports  =  {  hello,  bye  }
//  Same  as:  module.exports  =  {  hello:  hello,  bye:  bye  }
```

 **11.2) Methods**
```js
const  App  =  { 
 start  () 
  {
     console.log('running')
  }
}
//  Same  as:  App  =  {  start:  function  ()  {···}  }
```

 **11.3) Getters and setters**
```js
const  App  =  {
   get  closed  ()  {
      return  this.status  ===  'closed'
    },
   set  closed  (value)  {
      this.status  =  value  ?  'closed'  :  'open'
    }
}
```
 **11.4) Computed property names** 
```js
let  event  =  'click' let  handlers  =  {
[`on${event}`]:  true
}
//  Same  as:  handlers  =  {  'onclick':  true  }
```

 **11.5) Extract values**
```js
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**
```js
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
```

*import* is the new  require() .

 **12.2) Exports**
```js
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**
```js
function*  idMaker  ()  { let  id  =  0
while  (true)  {  yield  id++  }
}


let  gen  =  idMaker() gen.next().value	 //  →  0 gen.next().value	//  →  1 gen.next().value	//  →  2
```

 **13.2) For..of iteration**
```js
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!