Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Es 6

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 11

In this track, we will start by a little reminder of the web application.

Usually, web applications consist of three parts:

1. Front-end: This is where we create the user interface of the


application (a website for example). We use front-end
languages like HTML, CSS, JavaScript.

• Front-end can be a website, mobile app, TV app, Smart watch


app, etc.

1. Back-end: This is where we link the database to the front-end.


We use programming languages like JavaScript, C#, python,
PHP ...etc.

2. Database: This is where we store the data of the application


(products, customers, movies, etc.)

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

• Arrow Functions Array Enhanced Object Literals

• String interpolation Default Spread Variables

• Promises Import Export

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 :

Variable declaration: Let


ES6 provided a new declaration keyword called “let”.
Whenever we declare a variable with let, it will be defined only inside the block that contains the
declaration.
In other words, it’s only defined inside the curly brackets {} that contains the let declaration
ES6 also introduce the keyword const which allows us to declare constants.
When we are dealing with fixed values, using const will reduce bugs and unexpected behaviors.

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 };

One last thing, if we have these conditions:

1. Exactly only one instruction.

2. That instruction is a return statement.


We can omit the curly brackets {} and the return keyword.
Below is an example :

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

const f = _=>_ f(true) retourne true


const f = ()=>{true} retourne undefined

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)
}

Array function for each()


Now, let’s look at the .forEach() array function.
Suppose we want to perform an action on every element on a given array. The forEach method is
our way using predefined methods.
So what does it really do?
The .forEach() method will browse the array and execute the same instruction on every element in
this same array.
Let' see an example ! We want to browse the people array and alert every name in it:
const people = [{ name: 'Max' }, { name: 'Jack' }, { name: 'Marry' }]

// 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));

Array function: filter


Now let’s look at a more interesting array function. Imagine we have a cart full of groceries and
we want to keep only cheap products. If we consider an array of products where every product is an
object (as shown below).
Applying the filter method, we will have a new array that will eliminate all the products that have a
price more than 10 dollars.
const products = [{name:"Milk",price:15}, {name:"Water", price:9},
{name:"Bread", price:5}];

// 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);

Array function: map


ES6 also provided a function for array transformation using .map().
Let’s suppose we want to add two dollars to the price of each product in the array.
But you can ask what’s the difference between .forEach() and .map(). method? Well it’s very
simple, as we said the forEach execute the same instruction on every element in a given array, the
.map() method do the same thing but on copy of the array, like the original data still unchanged.
Don’t hesitate to try it yourself !
const products = [
{ name: 'Milk', price: 15 },
{ name: 'Water', price: 9 },
{ name: 'Bread', price: 5 },
]
// JavaScript
function changeProducts() {
for (let i = 0; i < products.length; i++) {
products[i].price += 2
}
return products
}

// ES6
const changeProducts = () =>
products.map(product => ({ ...product, price: product.price + 2 }));
console.log(changeProducts());
console.log(products);

Array function: reduce


Now let’s look the reduce() function.
It’s an inbuilt method that is used to apply a function to each element in the array. It reduce the
array to a single value.
The reduce() function executes the provided function for each value of an array from left-to-right.
The return value of a function is stored in an accumulator.
const data = [5, 10, 15, 20, 25]
const res = data.reduce((total, currentValue) => total + currentValue)
console.log(res)// 75

const newArray = [1,2,3].map(_=>true) [true, true,true]

const pounds = [11, 21, 16]


const avg = pounds.reduce((total, amount, index, array) => {
total += amount
if (index === array.length - 1) {
return total / array.length
} else {
return total
}
}, 0)
console.log(avg) 16

let a = ["one", "two", "three"].find(elm=>elm=="four")


console.log(a) undefined

["one", "two", "three"].forEach(elm=>alert(elm)) Alerts one string at a time

let result = [1, 2, 3].filter((a,index)=>index>2) []


Introduction
One of the most important approaches in software development is modularity.
So what's this modularity means? It means that we can split the code of a program into many
reusable pieces( usually grouped in files).
This approach was complicated before ES6. Now using this ECMAScript feature, it makes the code
too much easier.
That’s why ES6 brought two new keywords for this matter export and import.
JavaScript types that we can export or import are :
• String
• Number
• Function
• Objects
• Array
• Anything ...

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 () { ... };

//------ main.js ------


import myFunc from 'myFunc'

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”

Import id from “./student”

Import wonderfulId, {name} 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"

Object access chain


When working with objects, we can use the dot notation (also called object access chain) to get a
property of an object.
Let’s see an example :
let student = { address: { city: 'New York', country: 'USA' } }

console.log(student.address.city) // New York


console.log(student.address.country) // USA
Use of variable
But when dealing with deeply nested objects, we might end up with a long object access chain.
As we know, repeating code leads to duplicates, and duplicates are a problem. Some even say that
duplicates are the biggest software quality problem of all. So one of the alternatives is to use
variables as below:
let student = { address: { city: 'New York', country: 'USA' } }

let city = student.address.city


let country = student.address.country

console.log(city) // New York


console.log(country) // USA

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"}};

let {city, country} = address;

console.log(city) // New York


console.log(country) // USA

Destructuring can only be performed to an object False

let person = { name : "John", lastName:"Doe",age:28}

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

Problem of copying objects (references)


Imagine we have two arrays and we want to merge the values of the first array with the second
array.
Doing this in a traditional way requires a for loop and pushing all the elements of the two array to
a new array.
Note : Please notice that we can also use concat.
ES6 brought a more natural approach using the spreading operator that does the same thing.
let array1 = [1,2,3];
let array2 = [4,5,6];
// Using ES5
array1 = array1.concat(array2);
console.log(array1)// [1,2,3,4,5,6,4,5,6]
// Using ES6
array1 = [...array1, ...array2];
console.log(array1)// [1,2,3,4,5,6,4,5,6]

Create two copies of an object


The spreading operator made a huge improvement especially when dealing with objects. Copying
properties from an object to another used to be a bit tricky with the Object.assign() function (which
is a bit hard to work with).
Just like arrays, we add the spreading operator before the object, in this case we are spreading the
first and the second object like this:
let object1 = { firstName: 'John', lastName: 'Brown' }
let object2 = { age: 25 }

let newObject1 = { ...object1, ...object2 }


console.log(newObject1)
/* {
firstName:"John",
lastName:"Brown",
age:25
}*/

let newObject = {
name: 'Daniel',
name: 'John',
}
What’s the content of the “newObject” ? {name:”John”}

let student1 = {name:"John"}


let student2 = {name:"Mary"}
let newObject = {
student1, student2
}

What’s the content of the “newObject” ? {student1:{name:”John”}, student2:{name:”Mary”}}


et student1 = {name:"John"}
let student2 = {name:"Mary"}
let newObject = {
...student1,
...student2,
}
What’s the content of the “newObject” ? {name:”Mary”}

let student1 = {name:"John"}


let student2 = {name:"Mary"}
let newObject = {
...student1,
...student2,
name: 'Daniel',
}
What’s the content of the “newObject” ? {name:”Daniel”}

What’s the content of the “newObject” ?{student1:{name:”John”}, student2:{name:”Mary”}}


What’s the content of the “newObject” ?

{name:”Mary”}
What’s the content of the “newObject” ?

{name:”Daniel”}

You might also like