Es 6
Es 6
Es 6
Overview
ECMAScript is the JavaScript standard.
In 2012, the modern browser supported ECMAScript 5.1.
But since 2015, all browsers had used the newest implementation ECMAScript 2015 (ECMAScript
6 or ES6). It allows you to write less code and do more.
What is EcmaScript?
ES6 provides us with new features intended to facilitate software development.
The most used features are:Variable Declaration
Variables
As we already know, to declare a variable in JavaScript we used the keyword var.
Using ES6 guarantees another way to declaring our variables
ES6 Conventions:
• Use const by default.
• Use let if you have to rebind a variable.
• Use var to signal untouched legacy code.
When using var inside blocks like for loops, while loops, if statement, and others, the variable will
always be allocated until the end of the execution (even after the end of the block). This allocation
can lead to memory leak and unexpected bugs.
Notice in the example below that the variable i is still defined even after the for loop :
Attempting to change variables, which are declared with const, will raise an
error.
Definition
Usually, when displaying or returning a message containing variables, we always end up with a lot
of plus signs “+” (as shown below).
Fortunately, ES6 introduced a new way to combine strings and variables using special quotes ``
called template literals.
To create the special apostrophe ( ` ) you can click alt+7 or click the ~ button. It depends on your
keyboard. For different keyboards: Link
Example
In conclusion, template literals can be used to:
• Make multiline string.
• Create expressions.
• Put variables inside a string.
Arrow functions
ES6 is mostly about having an optimized and short code.
ES6 Arrow functions are a more concise syntax for writing function expressions.
Below is an example of a simple function with no arguments :
// JavaScript (ES5)
function multiply() { return 2 * 3; };
// ES6
const multiply= () => { return 2 * 3 };
If we have one or multiple arguments, we just add them between the parentheses.
Below is an example :
// JavaScript (ES5)
function multiply(x,y) { return x * y; };
// ES6
const multiply = (x,y) => { return x * y };
Argument
Arrow function are by design anonymous function (means that can be created without a name).
It’s the reason why, we assign it - by convention- to a variable that we invoke it whenever we want.
Another amazing feature that JavaScript provide is the possibility of passing a function as an
argument to another function.That’s what we call Higher Order Function or first class
function.This sound a little bit confusing but don’t panic, here is an example to make it easier to
understand.
let sayHello = () => alert`Hello`;
let sayBye = () => alert`Bye`;
//sayHello(); // “Hello” will be alerted
// Let’s create a function that takes an argument and call it as if it was a
function
let doSomething = somethingToDo => {
somethingToDo();
};
// Now any function we send to “doSomething()” function will be called right
away
doSomething(sayHello); // “Hello” will be alerted
doSomething(sayBye); // “Bye” will be alerted
Dealing with array in JavaScript can be a little bit complicated, and hard to code, here is an example
to explain our point of view. We want to alert The index of the name Jack in the array people
const people = [{ name: 'Max' }, { name: 'Jack' }, { name: 'Marry' }];
let i = 0;
while (i < people.length && people[i].name != 'Jack') {
i++;
}
if (i !== people.length) {
alert('John is in ' + i);
} else {
alert('Cannot find John');
}
Array functions
This is why, ES6 provides additional predefined functions to make working with arrays easier.
We are going to cover some of the important ones, such as:
• .find()
• .forEach()
• .filter()
• .map()
• .reduce()
Suppose that we want to find an element in an array, we would think about a for loop or a while
loop to do so.
On the other hand using ES6 find() function will make it very easy.
The find method is higher order function, so it takes a function as parameter, the parameter function
define the criteria of finding the desired element in the array
The find() method will return the value of the first element that satisfy the search criteria.
Here is an example to understand more:
const people = [{ name: 'Max' }, { name: 'Jack' }, { name: 'Marry' }]
// JavaScript
function findPerson(name) {
for (let i = 0; i < people.length; i++) {
let person = people[i]
if (person.name == name) {
return person
}
}
}
// ES6
function findPerson(name) {
return people.find(person =>person.name == name)
}
// JavaScript
function showEachOne(name) {
for (let i = 0; i < people.length; i++) {
alert(people[i].name)
}
}
// ES6
const showEachOne = name => people.forEach(person => alert(person.name));
// JavaScript
function filterProducts() {
let cheapProducts = [];
for (let i = 0; i < products.length; i++) {
if (products[i].price < 10) cheapProducts.push(products[i]);
}
return cheapProducts;
}
// ES6
const filterProducts = () => products.filter(product => product.price < 10);
// ES6
const changeProducts = () =>
products.map(product => ({ ...product, price: product.price + 2 }));
console.log(changeProducts());
console.log(products);
Type
Let’s suppose we want to use a code created in another module, the only thing that we have to do is
to import that module in our work file.
The two types of export are:
• Named exports: Zero or more exports per module
• Default exports: One per module
Named export
A module can export multiple things by prefixing its declarations with the keyword export. This
type of exports are distinguished by their names. In order to import this type we include the name
inside a curly brackets. We can also esport every module in the file using the * symbol an alias
using the keyword ‘as’.
//------ lib.js ------
export function square(x) {
return x * x;
}
export const sum = (x) => {
return x + x;
}
//------ main.js ------
import { square, sum } from 'lib' ;
import * as library from 'lib' // this means import every exported module in lib
and use the alias library
Default export
Unlike the named export, the default export give us the right to export only one default module per
file.
During the import declaration we can name the imported module whatever we want as shown in the
example below :
//------ myFunc.js ------
export default function funcName () { ... };
When we import a variable from a file, we need to specify the same name mentioned in the other
what’s the correct way?
named export
How can we import this variable that exists inside a file called student.js ?
export let id = 30;
import {id} from “./student”
/ student.js
export default let id = 30;
export const name = "Mary";
We have a file called student.js, which are the ones that are correct ?Import myId from “./student”
If we have in a file: export const f1 = ()=>{...} export const f2 = ()=>{...} what should we do to
import them:import {f1, f2} from "./file"
ES6 Destructuring
Variables solves the issue of redundant code. But, it makes the code longer and harder to read. This
is where the destructuring came into existence. In simple words, the destructuring assignment
syntax is a JavaScript expression that make it possible to unpack values from arrays, or properties
from objects, into distinct variables.
All we need to do is to put the variable inside two curly brackets in the declaration.
Notice : the variable must have the same name as the property inside the object.
You would do something like this:
let { address } = {address:{city:"New York", country:"USA"}};
Choose the correct way to pull the value of name from object person using destructure
let { name } = person
Can we perform destructuring on nested object? True
let newObject = {
name: 'Daniel',
name: 'John',
}
What’s the content of the “newObject” ? {name:”John”}
{name:”Mary”}
What’s the content of the “newObject” ?
{name:”Daniel”}