Understanding ES6 Functions, Objects, and Asynchronous Features
This article will be covering the following:
- Arrow functions
- Destructuring Assignment
- Asynchronous Features
- Promises
Arrow Functions
Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors. Arrow functions can be set to a variable.
Syntax examples of arrow functions:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
//ADVANCED:
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
In the past,
const person = {
first: "Roger",
actions : ['lift','code','beer'],
displayActions: function() {
this.actions.forEach(function(action){
let str = this.first + 'likes to ' + action;
console.log(str)
})
}
}
person.printActions()
//We will get a type error because this has fallen out of scope.
//It cannot see first which is my name.
//This can be fixed by attaching a .bind(this) at the end of the function.
....
displayActions: function() {
this.actions.forEach(function(action){
let str = this.first + 'likes to ' + action;
console.log(str)
}.bind(this))
...
//Now thanks to an arrow function we can simply and make sure this is bind to the function as follows.
...
displayActions: function() {
this.actions.forEach(action=>{
let str = this.first + 'likes to ' + action;
console.log(str)
})
...
Destructuring Assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
You are able to set variable names for a particular position within an array or object.
let array = ["Roger", "Shawn", "May", "Ray","Mark"]
//We can alter the array above as follows:
[first,,manager, ...students] =["Roger", "Shawn", "May", "Ray","Mark"]
//which will allow us to use first = Roger, ...students = ["Ray","Mark"]
We can use desctructuring assignment with objects as well.
let car = {
make: "Honda",
model: "CRV",
color: "red",
year: "2018",
}
//Usually you can use car.make which we are familiar with. Below I will explain a different way it can be used
//With this information we can create a function that will allow us to abstract the information provided in the object.
function carMarketing({year, make, model}){
return `You are looking at the new ${year} ${make} ${model}`
}
//When we log the function we will interpolate the object data to a sentence.
//within the function we used the curly boi's to take out the info we want from the object. When we pass the object the function knows to destructure the data.
carMarketing(car)
Asynchronous Features
What will be covered
- Explanation of Synchronous and Asynchronous code
- Promises
- Fetch
- Async and await
- Synchronous && Asynchronous
Javascript allows for us to make asynchronous and synchronous calls.
- With synchronous code if we have two blocks of code (C1, C2), C1 goes before C2, then C2 cannot begin to run until C1 has finished executing.
- Real world: With sync it is similar to when you are trying to buy tickets in person at a movie theater. You have to wait for everyone ahead of you to purchase their tickets before you can buy your own.
- With asynchronous code we are able to execute code without having to wait for other functions to finish running. In the code above, C2 can run and finish before C1 has finished completing executing. C1 can be scheduled to run in the future and that won’t interrupt C2 or any other code block after.
- Real world: With async it is similar to when you order your food at a restaurant. You and other guest can order your food at the same time or before/after one another, but based on your request your food may be ready before the other guests food is. If you order a drink only and they order steak, it may be likely that your order will be finished sooner than theirs and your order will be served first.
Note: asynchronous does not mean the same thing as concurrentor multi-threaded. JavaScript can have asynchronous code, but it is generally single-threaded.
In the example above the first console.log and the last will be called first, followed by the third, and finally the last one.
The best use for Asynchronous functions are with fetch calls.
//Simple fetch call
fetch(url)
.then(response=>response.json())
.then(json=> //do something with the json data
)
Using the .then allows for Async to work once the previous function has completed.
Promises
Async functions use the Promise object to help it handle the calls requested. The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
//Syntax
new Promise( /* executor */ function(resolve, reject) { ... } );
Promises takes in two parameters, resolve and reject. At it’s core, we need to say what we want to do if it is able to resolve/execute and retrieve the data we want or what do to if the call is rejected.
Below you can see an example of what happens when we resolve the promise with correct data and without.
fetch
Fetch by default is asynchronous. The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
The fetch specification differs from jQuery.ajax() in two main ways:
- The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
- By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
- Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.
//Basic fetch call using es5
fetch('http://example.com/api.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
//Using es6
fetch('http://example.com/movies.json')
.then(response=>response.json())
.then(json =>console.log(json))
// fetch calls presented are mainly used for GET calls
To use fetch with all other RESTful calls you will need to pass a second parameter. For other RESTful calls that require params I prefer to set them up like the example below.
//Declare the url, as a preference at top so it's easier to change.
const url = 'http://example.com/api.json'
//save the data you want to pass in to a body variable.
const body = {
data: "data being submitted",
}
//Configure your method, headers, and body with the data you want executed.
// As a preference it is clean code on what is being passed in.
const config = {
method: "POST", //Will be replaced with patch or other method
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body)
};
fetch(url, config)
.then(res=>res.json())
.then(json =>console.log(json))
Async and await
async and await allows you to write cleaner code and make use of async behavior. Check out the example below which goes over what happens when we do and do not use await.
Checkout Part 1 — What is ES6 (ECMAScript 6), the standard of JavaScript, and it’s features?
Connect and follow me on social media:
I am available for freelance or career opportunities, please gmail me!!
This is a great read! Awesome Roger.