Do you know ES6 - Part 1

2019-02-28

ES6 its JS, ES6 is about the next generation of Javascript.

ES6 is so useful because all the ES6 features React, Angular and Vue apps typically use. In general, ES6 allows us to write clean and robust react apps and this help us to do more powerful things.

Content:

  • Let and const
  • Arrow functions
  • Modules (Exports & Imports)
  • Classes
  • The threeDots ...
  • Destructuring

Let and const

Let and const are different ways of creating variables. We have var to create a variable in js but with ES6, There, two different keywords were introduced, let and const. Var still works but you're highly encouraged to use let and const Let is the new var, you use it for create a variable with value. But the most important point here is use let if you want to create a variable that really is variable. Use const if you plan on creating a constant value, so something which you only assign once and never change.

In normal JS, We use var keyword to create a variable

var myName = "Mohamed";
console.log(myName);

myName = "Khaled";
console.log(myName);

In ES6, We can use let keyword instead of var to create a variable

let myName = "Mohamed";
console.log(myName);

myName = "Khaled";
console.log(myName);

Also we can use const to create a constant variable. That means we can't reassign this value In the next example, We get an ERROR because we try to reassign a constant variable

const myName = "Mohamed";
console.log(myName);

myName = "Khaled"; //ERROR
console.log(myName);

Arrow functions.

Arrow functions is a different syntax for creating Javascript functions. A normal javascript function of course looks like this.

function printName(name) {
  console.log(name);
}

printName(); //undefined
printName("Mohamed"); //Mohamed

But Arrow functions:

const printName = (name) => {
  console.log(name);
};

printName();
printName("Mohamed");

There some alternatives to this syntax If we have one argument

const printName = (name) => {
  console.log(name);
};

printName();
printName("Mohamed");

If we have a function which receives no arguments, we need to pass an empty pair of parentheses

const printName = () => {
  console.log("Mohamed");
};

printName();

If we have a function which receives more than one argument, we need parentheses

const printName = (name1, name2, age) => {
  console.log(name1, name2, age);
};

printName("Mohamed", "Khaled", 23);
//Mohamed
//Khaled
//23

Also we can update our function body

const mul = (number) => {
  return number * 5;
};

console.log(mul(3)); //15

We can update this function and remove braces and retrun keyword

const mul = (number) => number * 5;
console.log(mul(3));

We can update also

const mul = (number) => number * 5;
console.log(mul(3)); //15

Modules (Exports & Imports)

We can split our code over multiple files, HOW? We have to import them in the correct order in out html files, So we can import content from another file

Example, If we have person.js file that have an object

//Object
const person = {
  name: "Mohamed",
};

export default person;

If we have another file utility.js, We can export multiple things

export const printMohamed = () => {
  console.log("Mohamed");
};

export const mul = (number) => number * 5;
export const baseData = 10;

We can import this somewhere else. For example this file app.js

//Notice: We can name person whatever we want because it's the default
import person from "./person.js";
import prs from "./person.js";

We should use curly braces to explicitly target specific things from that file

import { baseData } from "./utility.js";
import { mul } from "./utility.js";

We can assign an alias with any name you choose after as keyword

import { mul as multiply } from "./utility.js";
import { printMohamed as mkhy } from "./utility.js";

If we have multiple named exports in a file and we want to import all of them, We use special character * and then assign an alias

import * as bundled from "./utility.js";

If we have more than once and we want to import special exports

import {baseData},{printMohamed} from './utility.js'

Classes

Classes are blueprints for objects, Class can have both properties and methods

Here's We created Person class that has name property and mul method. Then we created an object from this class

//Create class
class Person {
  name = "Mohamed";
  mul = (number) => number * 5;
}

//Use class, use new keyword
const myPerson = new Person();

console.log(myPerson.name); //"Mohamed"
console.log(myPerson.mul(3)); //15

Another example, We created class that has a constructor and print method. Then we created an object from this class

//Create class
class Person {
  //Default function method
  constructor() {
    this.name = "Mohamed";
  }

  printMyName() {
    console.log(this.name);
  }
}

//Create an instance or object
const person = new Person();
person.printMyName(); //"Mohamed"

What if we want to make an inheritance? Here we use super keyword. super keyword It's a keyword and it simply executes the parent constructor

//Create Human class
class Human {
  constructor() {
    this.gender = "male";
  }

  printGender() {
    console.log(this.gender);
  }
}

//Create Person class
class Person extends Human {
  constructor() {
    super();
    this.name = "Mohamed";
  }

  printMyName() {
    console.log(this.name);
  }
}

//Create an instance or object
const person = new Person();
person.printMyName(); //"Mohamed"
person.printGender(); //"male"

Pay attention in the next important case: Here our person class extends from Human class but person class has it's own properties and methods.

class Human {
  //Default function method
  constructor() {
    this.name = "Mohamed";
    this.gender = "male";
    this.age = 23;
  }

  printGender() {
    console.log(this.gender);
  }
  printAge() {
    console.log(this.age);
  }
}

class Person extends Human {
  constructor() {
    super();
    this.name = "Sarah";
    this.gender = "Female";
    this.age = 35;
  }

  printMyName() {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName(); //"Sarah"
person.printGender(); //"Female"
person.printAge(); //35

Important notes on Classes, Properties and Methods

ES7 offers a different syntax of initializing properties and methods In ES6, Properties are like variables attached to classes or objects

constructor(){
	this.myProperty = 'value';
        this.name = 'Mohamed';
}

In ES7, We can assign a property directly inside our class so we skip the constructor function call. In fact behind the scene this will still be transformed to use constructor functions

myProperty = "value";
name = "Mohamed";

In ES6, As we discussed before, Methods are like functions attached to classes or objects

//myMethod () {...}
printMyName(){
    console.log(this.name);
}

In ES7: We use an arrow function as a property value so you have got no problems with the this keyword

//myMethod = () => {...}
printMyName = () => {console.log('Mohamed');}
printGender = () => {this.gender);}
printMyName = () => {this.name);}

In the next example, We can get rid of the constructor in the human class and get rid of the this keyword. Also we convert our methods to arrow functions. Finally, We no longer need to call super keyword. Pay attention: If you run it on JSbin, You will get an error because doesn't recognize the syntax. So you actually need to choose ES6/Babel

class Human {
  gender = "female";

  printGender = () => {
    console.log(this.gender);
  };
}

class Person extends Human {
  name = "Mohamed";
  gender = "male";

  printMyName = () => {
    console.log(this.name);
  };
}

const person = new Person();
person.printMyName(); //"Mohamed"
person.printGender(); //"male"

The threeDots ...

  • The spread and the Rest operators called the threeDots
  • The operator is just three dots ...
  • The spread operator is used to split up array elements or object properties. In other words, To copy arrays or add properties to an object whilst safely copying that old object. The spread operator takes out all elements, all properties and distributors them in a new array or object or wherever you are using it

EX1 ... With array

const numbers = [1, 2, 3];
const newNumbers = [numbers, 4, 5];
console.log(newNumbers); //[[1, 2, 3], 4, 5]

const spreadNumbers = [...numbers, 4, 5];
console.log(spreadNumbers); //[1, 2, 3, 4, 5]

EX2 .. With object

const oldPerson = {
  name: "Mohamed",
};

const newPerson = {
  ...oldPerson,
  age: 23,
};

console.log(newPerson);

Output [object Object] { age: 23, name: "Mohamed" }

  • The rest operator is used to merge a list of function arguments into an array and we use it in a function argument list
const filterFunc1 = (...args) => {
  return args.filter((el) => el === 1);
};

console.log(filterFunc1(1, 2, 7, 1, 3, 8, 9, 1, 2)); //[1, 1, 1]

EX3

const filterFunc2 = (...args) => {
  return args.filter((el) => el === 1 || el === 2);
};

console.log(filterFunc2(1, 2, 7, 1, 3, 8, 9, 1, 2)); //[1, 2, 1, 1, 2]

Destructuring

  • Destructuring allows you to easily extract array elements or object properties and store them in variables
  • Destructuring is different than what spread operator do
  • Destructuring allows you to pull out single element or properties and store them in varables for arrays and objects

Array example:

[a, b] = ["Mohamed", "Khaled"];
console.log(a); //Mohamed
console.log(b); //Khaled

Object example:

myInfo1 = { name: "Mohamed" };
console.log(myInfo1.name); //Mohamed
console.log(myInfo1.age); //undefined

myInfo2 = { name: "Mohamed", age: 23 };
console.log(myInfo2.name); //Mohamed
console.log(myInfo2.age); //23

EX1

const numbers = [1, 2, 3];
[num1, num2] = numbers;

console.log(num1, num2);
//1
//2

EX2

const numbers = [1, 2, 3];
[num1, , num3] = numbers;

console.log(num1, num3);
//1
//3

EX3

const { name } = { name: "Mohamed", age: 23 };
console.log(name); //Mohamed
console.log(age); //undefined

EX4

const { name, age } = { name: "Mohamed", age: 23 };
console.log(name); //Mohamed
console.log(age); //23

Some reference: Read more about [let] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) Read more about [const ] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) Read more about [ES6 Arrow Functions] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

###Finally … [Here] (https://github.com/mkhy19/Crash-courses/tree/master/JS/ES6) is the repo, You can find all source code.