The 5 super powers of ES6

Search for a command to run...

No comments yet. Be the first to comment.
Disclaimer: Consistent with the honor code, no solutions are provided here, only hints to help troubleshoot two common errors While working on the Deep Learning capstone “Deploying a Sentiment Analysis Model” project, most of my time was spent troubl...

Over the past several months, I’ve had the fortune to develop Apps for Google Chromestore and one app that has more than half a million users (here’s my story, and be selected for Udacity’s Grow with Google. As a part of this scholarship I got the ch...

Udacity sponsors a three month first round “Grow with Google Challenge Scholarship”. When I applied to the Mobile Web Specialist track I was not sure what I would get out of Udacity. I considered myself a middling self-taught web programmer. (Here’s...

This post is about two ways to handle pagination (getting multipage results) in response to queries on Google and Zendesk APIs While most Web API provides multi page results to a call, most API documentation will only talk about how to get the first ...

This blog is about new ES6 features. Learning about ES6 is probably pretty straightforward for experienced folks. It wasn’t for me. As a part of Udacity’s Grow with Google challenge cohort where ES6 was covered, I see that I wasn’t alone. So here are 5 new ES6 features written by a newbie for other newbies.
Before we start: You know what a function and a parameter is
What it does The default function parameter allows you to set a default value for your parameter(s)

Why is it useful ? Not all parameters are created equal. Sometimes if a parameter value is missing the code can crash badly. default allows the programmers a nice safety net.
An example: Say you are writing a function that will perform a division by the value of one of its parameters. To avoid a division by zero you will have to do some detailed error checking.
function divide_old(a, b) {
/* We have to make sure we have the right number of arguments and their values are not 0. We are simplifying here and assuming we are dealing only with positive numbers
*/
if (arguments.length===2 && arguments[0]>0 && arguments[1]>0){
return arguments[0]/arguments[1]
}
else if(arguments.length===1 && arguments[0]>0){
return arguments[0]/1
}
}
With the default value for the parameters in ES6 you can now write code as follows
function divide(a, b = 1) {
return a / b;
}
This makes life a whole lot easier for both the user/caller of a function, who does not have to worry and of course for the function author.
For more see the MDN page
Before we start: you need to know what is a call to a REST API means and what JSON data is, and what JSON data processing is.
What it does: Provides programmers with a really simple way to make calls to a REST API
Why is it useful: REST APIs give you access to databases with rich information that your program can use. Before ES6 the most common ways of doing this was to use a third party library, with the most popular being jQuery’s ajax.
An example: The example shows the mechanics of a fetch call and getting some JSON data. If you have done things the old way I am sure you can immediately appreciate the benefits.
function fetch_simple (url) {
fetch(url)
.then (response => {return response.json()}) // JSON parsing done for you
.then(data => {
// do whatever you want to do with the data
})
.catch (err => {
console.log("===we have an error===")
console.log(err.stack)
})
}
For more see the MDN page
Before we start: You need to know arrays, and objects
What it does: It’s an iterable collection of unique elements. However this is not about what it is, but rather what it can help you do.
Why it is useful: You can very quickly remove duplicates from existing arrays.
To remove duplicates just create a set from an array and then convert that set back to an array.
const nums_with_duplicates = [1,5,7,8,5,8,23,45];
a_set = new Set(nums_with_duplicates);
const nums_unique = [a_set]// the [] changes the set back to an array
While both objects and the new ES6 Map also provide the support for unique elements, Set preserves the iteration order of its elements. So when we need a collection where the order of iteration and uniqueness matter, Set comes upon top.
The pattern [...new Set (array_with_duplicates)] will always give you an array with the duplicates removed. Nice, right?
Basic operations with a set
The code to walk a set is also nice and compact
for (const month of months) {
console.log(month)
}
For more see the MDN page
Before we start: you need to know what arrays and parameters are. Also an iterable object
What it does:
If you have been reading about ES6 and looking at code written in it I am sure you have seen the curious ... three dots popping up everywhere. These three dots have two names and two very different meaning in ES6. The naming and the meaning depends on what section of the code they appear:
... is called a rest parameter when used in function declaration, for example, in function foo (a, ...b){//do stuff}, the dots make b a rest parameter. The dots also mean that the second parameter is an array with an unspecified number of elements.
Any other place you see those dots they are spread operators. The spread operators most commonly appear in array literals like this: [...a, 4, 5,6] Here also the dots represent an array of unspecified number of elements.
The a must be an iterable object like arrays, strings and the ES6's new Maps and Sets.
Why is it useful: When used as rest parameters, the dots “pack” many variables in to an array. So in the function function foo (a, ...b){//do stuff} if we call foo with foo(5,6,9), this would mean that a is 5 and b, because of the three dots is an array[6,9]
When used as a spread operator the dots “unpack” variables. See the following function:
function bar (a, ...b){
console.log(bar);
/* [6,9,10] Note it only starts from the second number because the first parameter is not part of the spread operator */
console.log(...b);// 6 9 10 //notice it unpacks [6,9,10]
}
bar(5,6,9,10)
The first three dots are rest parameters and “pack” the variables into an array. The second set of three dots “unpack” the array into the individual elements. This makes it easier to work with arrays in functions.
An example
function foo (a, ...rest) {
console.log("\n\nvalue of the first param is " + a)
console.log("the rest of the params are in an array: ")
console.log(rest)
console.log("unpack them to a list as follows:")
console.log(...rest)
return "Done"
}
foo (5,6,9,11) // a will be assigned 5 and the rest will be [6,9,11]
foo (5,6,9,11, 2) // a will be assigned 5 and the rest will be [6,9,11, 12]
foo (5) // a will be assigned 5 and the rest will be empty
foo (5,6,[9,11]) // will be assigned 5 and the rest will be [6,[9,11]]
Copy and paste the above to the console to see how it works
Feel free to dig deep into many interesting usecases for rest parameters and spread operators.
But as a newbie I find the following two patterns very useful:
The spread operator make array concatenation much more natural.
joined_array = [...first_array, ...second_array, ...third_array]
You can combine it with ES6 Sets to remove duplicate from arrays
const unique = [...new Set(non_unique)];
For more see the MDN page and this MDN page too
Before we start: You need to know sets, arrays, parameters
What it does: Destructuring allows a programmer to break a compound structure like an array or an object down to its elements (or properties in case of objects) and assign those “destructured” pieces to variables. [a,b] = [1,2] is now a valid Javascript statement, which assigns 1 to a, and 2 to b.
Why it is useful: It makes code simpler and short. See example for more
Get rid of the pesky temp variable and three lines of code and swap variables in one shot.
var a = 1;
var b = 3;
[a, b] = [b, a]; //
console.log(a); // 3
console.log(b); // 1
returns like a Profunction f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
Create a duplicate free arrays in one shot. This one needs to know Sets too!
const unique = [...new Set(array_with_duplicates)];
Create a set from the array_with_duplicates array, this will remove the duplicates
Use the spread syntax to unpack the set elements
“destructure” the unpacked element back into an array
For more see the MDN page
Javascript takes on the big guns
Many languages (such as Perl) are famous for allowing programmers to express fairly complicated commands in just one line. Javascript was never known for this. With ES6 it is slowly getting there.
Consider the following array that contains the month names when the temperature dipped below a threshold.
const low_temp_months = ['January','January', 'February', 'March','November', 'December','December'];
As you notice there are some duplicates perhaps caused by multiple readings submitted for the same month. If you want the month names to be unique you can do the following:
Create a set from the low_temp_months array, this will remove the duplicates
Use the spread syntax to unpack the set elements
“Destructure” the unpacked element back into an array
All the three aspect can be implemented in a very nice one liner!
const winter_months = [...new Set(low_temp_months)];