JavaScript - Lesson 05
JavaScript - Lesson 05
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
• 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.
• 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
hoisted(); // Output: "This function has been expression(); //Output: "TypeError: expression
hoisted." is not a function
Array Object
console.log(example2); //1,2,3,4,5
console.log(example1); //1,2,3,4
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).
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.
// 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.
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.
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.
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!!!
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
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') );
.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.
• 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";
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