ES6 — What you need and what you should know.

Krina Soni
5 min readAug 23, 2018

ECMAScript is standard for JavaScript and along with the specification of its own, It publish version with more features each year and recent are ES6, ES7, and ES8.

Now, as it’s for additional features JavaScript developer must know some of common features which are very helpful to simplify your code.

Arrow Functions

The arrow functions has a shorter syntax and it does not have it’s own this or arguments. They can never be used as constructor.

That’s all about arrow functions. But it has made a big impact as there are ways it is useful and let’s catch on them.

Basic Syntax is () => { statements }
In which it will return something either explicitly or implicitly. Also it can have arguments. But arguments is simply a reference to the arguments of the enclosing scope.

var numbers = [1,3,4,6,8,9];
var final = numbers.map(() => { numbers.length }) //will return 6
var sum = (a,b) => { return a + b } //will sum and return it.
sum(3,5); // return 8 value

And this will return you length of array. You can see shorter syntax and clean code. where you can use it in is mostly arrays & their manipulation.
If you have array of objects of users and you need to show/get particular value then it can make your job done in fewer and simplified code.

var users = [{ “fname”: “Jon”, “lname”: “Snow” },
{ “fname”: “Cerci”, “lname”: “Lannister” },
{ “fname”: “Sam”, “lname”: “Tywell” }];
const surnames = users.map((user) => { user.lname });
console.log(users, surnames); //list surnames in array

Let’s see how can we use them in react and how does it prevent this bugs. And all we’ll see through example.

import { Component } from ‘react’;class Layout extends Component {
constructor(props) {
super(props);
this.state = {
name: { 'Cerci' }
}
}
call(){
this.setState({ name: ‘Tyrion’ });
} //1
call = () => {
this.setState({ name: ‘Tyrion’ });
}//2
render() {
return (
<div>
<button onClick={this.call}>Change Name </button> //1
<button onClick={this.call.bind(this)}>Change Name </button> //2
<button onClick={this.call}>Change Name </button> //3
<span>{this.state.name}</span>
</div>
)
}
}
export default Layout;

Few Cases will be as follow :

Arrow Functions Implementation in ReactJS

Template Literals

It is way how output variables in string.

console.log(“Hello ” + “ ” + fname + “ ” + lname);

In ES6, we have $ to make it easier like this.

console.log(`Hello ${fname} ${lname}`);

Var, Let & Const

var
var is statement used for defining or initializing value and it can be re-assigned.
Also, it will override the existing value if you update/ assign different value to var. For ex,

var a =10; 
console.log(‘a’ , a);
if ( 5 < 10){
a = 5;
console.log(‘inside if : a’ , a);
}
console.log(‘after if block’ , a);

Let
let is statement used for declaring local variable and it’s scope would be block-wise. Also It can be re-assigned but, it will not override it’s existing value.

For ex,

let a =10; 
console.log(‘a’ , a); // 10
if ( 5 < 10){
a = 5; // this will throw error
console.log(‘inside if : a’ , a); //5
}
console.log(‘after if block’ , a); //10

One more difference between let and var is you can define same variable using var keyword and it will not throw any exception and same thing you can not do using let. It will give you exception as Identifier has already been declared.

const
It can be used for values assigning for constants. As name suggests, value will be constant and will never be re-assigned throughout. Also it’s scope will be same as let keyword.

const a = 10 ; //one const named a 
if ( 5 < a){
const b = 20;
const a = 22; //second const named a but in different block
const b = 5; //this will throw error
console.log(‘inside if : ’ , a , b ); // 22 , 20
}
console.log(‘after if block’ , a); //10

Spread & Rest Operator

It allows an iterate such as an array expression/ string / object to be expanded in places where zero or more arguments or elements are expected.
It’s syntax is three dots ( … )

It can be used mostly in combining arrays, copying arrays, converting arguments to array, call functions without apply.
Let’s see examples for each :

Before using apply , 
function getData(x, y, z) { }
var args = [0, 1, 2];
getData.apply(null, args);Using Spread operator ,
getData(...args);

For combining array ,

var arr1 = [“first”,”second”,”third”];
var arr2 = [“forth”,”fifth”,”sixth”];
var arr3 = [ …arr1, …arr2, “seventh”];

For Copying & concatenating array, You just need to assign one array to another.

var tags= [“cool”,”funny”,”hot”];
var category = […tags]; //copy array
category.push(“joyous”, “young”);
var final = [...tags, ...category]; //concat array

For Math,

var arr = [2, 4, 8, 6, 0];
var max = Math.max(…arr);

Rest looks exactly like spread syntax, but is used for destructing arrays and objects. In a way, rest is the opposite of spread : spread ‘expands’ an array into its elements, while rest collects multiple elements and ‘condenses’ them into a single element.

let { name, age, ...rest } = { name: "test", age: 20, city: "NYC", job: "Developer"};
console.log(name); // test
console.log(age); // 20
console.log(rest); // { city: "NYC", job: "Developer" }

Generators

Generators are functions which can be exited and later re-entered & It returns Generator object.
To simplify this definition , Generator is special function which can be paused and resumed again from last point it paused.
You may use different declarative statements for it.

function* fname() {}
function *fname() {}
function * fname() {}

yield is an expression form which returns a value.
The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value as a boolean.

{ value: 'data', done: false/true }

Now, If your mind got stuck with all these theory, Let’s see example so you can understand what it means to have generator function & yielding.

function * call(){
console.log('before yield, all statements will get executed');
yield console.log(‘first’,1);
yield console.log(‘second’,2);
yield console.log(‘third’,3);
}
var data = call();
data.next();
//before yield, all statements will get executed
// console first 1 & return done :false
data.next();
// console second 2 & return done :false
data.next();
// console third 3 & return done :false
data.next();
// return done:true

If you return in generator function, statements after return statement will get ignored and done value will be true.

Use all of these features in daily life and be a pro !!
If you found this helpful, Please clap.
Thank You Everyone!!

--

--

Krina Soni

Passionate about places, photos and coding! Food is love !!