0% found this document useful (0 votes)
13K views

JavaScript - Lesson 05

The document summarizes key ES6+ features including: 1. Destructuring, template literals, let/const/var scoping, arrow functions, for-of loops, spread/rest operators, default parameters, import/export, promises and async/await. 2. It provides examples of destructuring objects and arrays, template literals, let/const/var block scoping, spread operator to copy arrays/objects, and rest operator to collect function parameters. 3. Key differences between named and default exports are explained along with examples of importing/exporting modules.

Uploaded by

Choudhry Traders
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13K views

JavaScript - Lesson 05

The document summarizes key ES6+ features including: 1. Destructuring, template literals, let/const/var scoping, arrow functions, for-of loops, spread/rest operators, default parameters, import/export, promises and async/await. 2. It provides examples of destructuring objects and arrays, template literals, let/const/var block scoping, spread operator to copy arrays/objects, and rest operator to collect function parameters. 3. Key differences between named and default exports are explained along with examples of importing/exporting modules.

Uploaded by

Choudhry Traders
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Lecture # 5

ES5+ features

Presented by:
Ahsan Ali Mansoor
4+ Years of experience / Team Lead (React JS)
Sr. Full Stack JavaScript Developer at eBridge.tech
ES6+ Cheat sheet
1. Destructuring 13. Promises , Async & Await
2. Template string / template literals 14. Sets
3. Let , const , var with function scope and block 15. High order array functions
scope 16. Classes
4. Hoisting
5. Arrow functions
6. For of loop
7. Spread operator
8. Rest Operator
9. Array.Includes
10. Default params
11. import and export
12. Trailing comma
Destructuring
• Destructuring with object

let user = {name : 'Ali', age : 28}


let { name, age } = user //before destructuring > name = user.name

• Destructuring with Array

var cars = ['suzuki' , 'Toyota']


let [first , second] = cars // before destructuring > first = cars[0]

• Destructuring with alias


let { name : n, age : a } = user
Console.log(n)
Template String / Literals
• Template string / literals: allows us to create multiline string and include variables as ${variable}.

• Syntax
let addressParts = { city : 'redwood' , state : 'california' , country: 'USA' }
let { city, state, country } = addressParts;
//before template string
let address = "My address is" + city + ", " + state + ", " + country
let address = `My address is ${city}, ${state}, ${country}`
console.log(address);
let, const, var
Understand Scope:
The scope of a variable is controlled by the location of the variable declaration, and defines the
part of the program where a particular variable is accessible.
Global Scope: Variable accessible throughout the file.
Block/Local Scope: Variable accessible only within the scope where it is created i.e. within a if
condition or a loop block.

Out of any Block If or Loop Block Function Block


let Global Scope Block scope Block scope
const Global Scope Block scope Block scope
var Global Scope Global Scope Block scope

Declaration without value Mutate value Redeclare within same scope


let Allowed Allowed Allowed
const Not Allowed Not Allowed Not Allowed
var Allowed Allowed Allowed
Let, const, var scoping
Function Scope: if we define variable within Block scope: i.e in if else block or loop
function even with var it won't accessible to
If we define variable with in block scope with
outer world
var then its accessible to outer world but with
let and const not.
function add(a,b){
var c = a+b; if(condition){ var c = 10; }
return c; console.log(c) //10
}
console.log(c) //undefined if(condition){ let c = 10; }
console.log(c) //undefined
NOTE: Variables defined without any
keyword(ver, let) in function scope
becomes global. if(condition){ const c = 10;}
console.log(c) //undefined
Hoisting variables
• Hoisting is a JavaScript mechanism where variables and function
declarations are moved to the top of their scope before code execution.

• Inevitably, this means that no matter where functions and variables are
declared, they are moved to the top of their scope regardless of whether
their scope is global or local.

• Of note however, is the fact that the hoisting mechanism only moves the
declaration. The assignments and function expressions are left in place.
Hoisting functions

Function Declarations Function Expressions


These are of the following form and are hoisted Function expressions, however are not hoisted.
completely to the top. Now, we can understand
why JavaScript enable us to invoke a function
seemingly before declaring it.

hoisted(); // Output: "This function has been expression(); //Output: "TypeError: expression
hoisted." is not a function

function hoisted() { var expression = function() {


console.log('This function has been hoisted.'); console.log('Will this work?');
}; };
Hoisting Summary

Do Hoist Don’t Hoist


• Variables • Variable Assignments

• All var to global scope except inside function • Function expressions


block
• Classes
• Let & const to their block scope
• Just like functions expressions, arrow
• Functions Declaration / Function Statements functions aren't hoisted — only function
declarations are.
• Variables defined in function scope without
any keyword hoisted to global
Spread operator …
Spread operator creates a whole new object / array from the given array / object.

Array Object

let example1 = [1,2,3,4] let objOne = {name: "sabir", class: 18}


let example2 = […example1] let objTwo = {...objOne}
example2.push(5) objTwo.age = 30

console.log(example2); //1,2,3,4,5
console.log(example1); //1,2,3,4

Add new element Add new property


[…example2, 6] {...objTwo, habbit:"cricket"}
Usage example of Spread operator
We have an array of fruits
fruits = ["one", "two", "Banana"]

We want sort that array but do not want to change the original array
[...fruits].sort()

It will return the sorted copy of original array which we store in a variable
let newFruits = [...fruits].sort()
Rest operator …
Seems like spread operator but it’s a bit different.
It will give all function arguments( As an array).

Obsolete way Rest Operator


function add(nums){ function newAdd(...nums){
console.log(arguments); console.log(nums)
} }
newAdd(1,2,3,4,5)
add(4,5,6,7); Output will be: [1, 2, 3, 4, 5]

//All remaining params


function myFun (a, b, ...theArgs) { // …..}
myFun("one", "two", "three", "four", "five")
Default PARAM
Can assign default values to a function’s arguments/Parameters.

function user(user = 'test', pass='mypass'){


console.log(user);
console.log(pass);
}
user();
user('sabir', 'nopass');
Import and export
It allows us export data set / function / module from a file and import in
another to use there.

File: example.js
export const data = [1,2,3]

File: function.js
Import {data} from example.js
console.log(data)

Note: type="module“ attribute required in script tag while using import/ export.
Named Export vs Default Export
ES6 provides two ways to export a module from a file: named export and
default export.

11.1 - Named Export:


With named exports, one can have multiple named exports per file. Then
import the specific exports they want surrounded in braces. The name of
imported module has to be the same as the name of the exported module
Named Export vs Default Export
// ex. importing a single named export
import { MyComponent } from "./components";

// ex. importing multiple named exports


import { MyComponent, MyComponent2 } from "./components";

// ex. giving a named import a different name by using "as":


import { MyComponent2 as MyComp } from "./components";

// exports from ./components.js file


export const MyComponent = () => {}
export const MyComponent2 = () => {}
Named Export vs Default Export
Import all the named exports into an object:

import * as MainComponents from "./components";


// use MainComponents.MyComponent and MainComponents.MyComponent2 here
Named Export vs Default Export
11.2 - Default Export:
One can have only one default export per file. When we import we have to
specify a name and import like:

// Import
import MyDefaultComponent from "./MyDefaultExport";

// Export
const MyComponent = () => {}
export default MyComponent;
The naming of import is completely independent in default export and we
can use any name we like.
Trailing comma
Es6+ allows us trailing comma at the end of object property

Let user = {
name: “john”,
age: 32,
}
JavaScript Promises and Async/Await:
Using promises, we can write asynchronous programs in a more manageable
way. Using Async/Await syntax, a promise-based asynchronous code can be
written in a synchronous format which saves a lot of time and code becomes
scalable.
JavaScript Promises
JavaScript is synchronous means: JavaScript executes code in a single
thread, which makes it blocking. Let’s take a simple example of calling three
functions in series.
function a() { console.log( 'result of a()' )}
function b() { console.log( 'result of b()' )}
// call in sequence
a(); console.log('a() is done!');
b(); console.log('b() is done!');

Output
"result of a()"
"a() is done!"
"result of b()"
"b() is done!"
14 – JavaScript Promises
JavaScript is synchronous
As we can see from the above result, each function call and console.log
statement is executing in series AKA in a synchronous manner.

This means until the function has returned, the next line of code won’t be
called. By default, a function with no return statement returns undefined
value.
JavaScript Promises
We need asynchronous behavior.
Using Web APIs, some JavaScript jobs can be transferred to other threads.

Handling of AJAX request or REST API call should be done on a different


thread, else our main thread would be blocked until the network response is
received. This would be a horrible UX for the user, as his/her screen would
just freeze for several seconds or minutes.
Make JavaScript asynchronous
Two ways to make JavaScript Asynchronous.

1- Callback functions which leads to callback Hell.


2- Promises
Asynchronous JavaScript with Callbacks
Web APIs are APIs that extends JavaScript functionality to perform
asynchronous tasks. For example, setTimeout is a Web API that performs
some action after a given delay.

Basically, setTimeout(callback, delay) function takes a callback and stores it


temporarily. It waits for delay given in milliseconds and then pushes the
callback function in the stack. Then the callback function gets executed. This
is basically how all Web APIs work.

Web APIs is not a part of the JavaScript standard. They are not included in
the JavaScript engine. Instead, they are provided by the browser or server-
side JavaScript frameworks like Node.js
Asynchronous JavaScript with Callbacks
Let’s add asynchronous nature with callbacks to our earlier example and see
the problem with it.

See Code: https://codesandbox.io/s/synchronous-functions-uuqjq

The answer lies in the callback function itself. A callback function according
to its definition is a function which will be called when a job is finished. Let’s
pass a callback function to each of our functions a, b, and c which contains
console.log statement in it.

Code Here: https://codesandbox.io/s/asynchronous-nature-with-callbacks-2qm6z


Asynchronous JavaScript with Callbacks
Callback Hell!!!

But still, we haven’t resolved the issue. What we want is, the jobs should
execute in series. What we can do to make sure a() completes first and then
b() and then c(). Welcome to callback hell!

The simple idea is to call b() in the callback of a because that’s where we
know that a() has done its job and similarly call c() in the callback of a.
Asynchronous JavaScript with Callbacks
Callback Hell!!!

Code Here: https://codesandbox.io/s/callback-hell-0sxt2?file=/src/index.js


a(() => b(() => c(() => console.log("c() is done!"))));

In the above example, we have nested the callback which guarantees the
series operation of the function. This nesting of callbacks is called
as Callback Hell. This is literally a hell because if we had more than 3
function calls, the code could get messier pretty quickly.
Promises , Async & Await
Promises are used to handle asynchronous operations in JavaScript. Promises are the ideal choice for
handling asynchronous operations in the simplest manner. They can handle multiple asynchronous
operations easily and provide better error handling than callbacks and events.
• Benefits of Promises
• Improves Code Readability
• Better handling of asynchronous operations
• Better flow of control definition in asynchronous logic
• Better Error Handling

• A Promise has four states:


• fulfilled: Action related to the promise succeeded
• rejected: Action related to the promise failed
• pending: Promise is still pending i.e not fulfilled or rejected yet
• settled: Promise has fulfilled or rejected (not pending)
Promises
A promise can be created using Promise constructor.

var promise = new Promise((resolve, reject) => {


//do something
});

Parameters
• Promise constructor takes only one argument,a callback function.
• Callback function takes two arguments, resolve and reject
• Perform operations inside the callback function and if everything went well then call resolve.
• If desired operations do not go well then call reject.
Promises
Example
var myPromise = new Promise((resolve, reject) => {
const x = 'eBridge’;
const y = 'eBridge’;
if(x === y) { resolve() } else { reject() }
});
//Promise consumption
myPromise
.then(() => console.log('Success, You are a GEEK') )
.catch(() => console.log('Some error has occurred') );

//Promise returns two things


• Promise state
• promise value //undefined by default(as the every function returns) if we are not returning anything
Promises with & without returning value
Promises - Promise Consumers
Promises can be consumed by registering functions using two methods
1- then
2- catch

1- then() is invoked when a promise is either resolved or rejected.


Parameters: then() method takes two functions as parameters.
First function is executed if promise is resolved and a result is received. Second function is executed if
promise is rejected and an error is received. (It is optional and there is a better way to handle error using
.catch() method

.then(function(result){
//handle success
}, function(error){
//handle error
})
Promises - Promise Consumers
2- catch() is invoked when a promise is either rejected or some error has occurred in
execution.

Parameters:
catch() method takes one function as parameter.
Function to handle errors or promise rejections.(.catch() method internally calls .then(null,
errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )

.catch((error) => {
//handle error
})
Network Calls (http requests / REST API)
• A way to get data from server.

• An API is an application programming interface. It is a set of rules that


allow programs to talk to each other. The developer creates the API on
the server and allows the client to talk to it.

• REST determines how the API looks like. It stands for “Representational
State Transfer”. It is a set of rules that developers follow when they
create their API. One of these rules states that you should be able to get
a piece of data (called a resource) when you link to a specific URL.

• Each URL is called a request while the data sent back to you is called
a response.
what is fetch in JavaScript
The Fetch API provides a JavaScript interface for accessing and
manipulating parts of the HTTP pipeline, such as requests and
responses. It also provides a global fetch() method that provides
an easy, logical way to fetch resources asynchronously across the
network.
Promises for Network Calls
Use fetch() for network call:

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));
Async await Syntax for http requests
Async await Syntax
const api = "https://jsonplaceholder.typicode.com/todos/1";

Syntax: ES6 syntax:

async function getData(){ const getData = async () =>{


const res = await fetch(api); const res = await fetch(api);
const json = await res.json(); const json = await res.json();
console.log(json); console.log(json);
} }
getData(); getData();
https://codesandbox.io/s/http-call-with-asyncawait-4zu1h?file=/src/index.js
Sets
• A set is a collection of items which are unique i.e no element can be
repeated.
• Set in ES6 are ordered: elements of the set can be iterated in the insertion
order.
• Set can store any types of values whether primitive or objects.
• Set take an array as an argument and output will be an object.

Methods
• add()
• delete()
• has()
• clear()
Sets
var numArray = [1,1,2,2,2,3,3]
const uniNumber = new Set(numArray) //will return unique values from numArray as an object
typeof uniNumber // output "object“
console.log([… uniNumber]); //output as an array, by taking an empty array and make a copy of
object using spread operator

Applying Methods
uniNumer.add(5) //add and return new object
uniNumer.delete(5) //delete and return true or false
uniNumer.size //return number integer 3
uniNumer.has(1) // return true or false

Loop through set


uniNumer.forEach((item) => console.log(item))

You might also like