by rajaraodv

Check out these useful ECMAScript 2015 (ES6) tips and tricks

Photo by Glenn Carstens-Peters on Unsplash

EcmaScript 2015 (aka ES6) has been around for couple of years now, and various new features can be used in clever ways. I wanted to list and discuss some of them, since I think you’ll find them useful.

If you know of other tips, please let me know in the comment and I’ll be happy to add them.

1. Enforcing required parameters

ES6 provides default parameter values that allow you to set some default value to be used if the function is called without that parameter.

In the following example, we are setting the required() function as the default value for both a and b parameters. This means that if either a or b is not passed, the required() function is called and you’ll get an error.

const required = () => {throw new Error('Missing parameter')};
//The below function will trow an error if either "a" or "b" is missing.const add = (a = required(), b = required()) => a + b;
add(1, 2) //3add(1) // Error: Missing parameter.

2. The mighty “reduce”

Array’s reduce method is extremely versatile. It is typically used to convert an array of items into a single value. But you can do a lot more with it.

🔥Tip: Most of these tricks rely on the initial value being an Array or an Object instead of a simple value like a string or a variable.

2.1 Using reduce to do both map and filter *simultaneously*

Suppose you have a situation where you have a list of items, and you want to update each item (that is, map) and then filter only a few items (that is, filter). But this means that you would need to run through the list twice!

In the below example, we want to double the value of items in the array and then pick only those that are greater than 50. Notice how we can use the powerful reduce method to both double (map) and then filter? That’s pretty efficient.

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {    num = num * 2; //double each number (i.e. map)    //filter number > 50  if (num > 50) {    finalList.push(num);  }  return finalList;}, []);
doubledOver50; // [60, 80]

2.2 Using “reduce” instead of “map” or “filter”

If you look at the above example (from 2.1) carefully, you’ll know that reduce can be used to filter or map over items! 🔥

2.3 Using reduce to balance parentheses

Here’s another example of how versatile the reduce function is. Given a string with parentheses, we want to know if they are balanced, that is that there’s an equal number of “(“ and “)”, and if “(“ is before “)”.

We can easily do that in reduce as shown below. We simply hold a variable counter with starting value 0. We count up if we hit ( and count down if we hit ) . If they are balanced, then we should end up with 0.

//Returns 0 if balanced.const isParensBalanced = (str) => {  return str.split('').reduce((counter, char) => {    if(counter < 0) { //matched ")" before "("      return counter;    } else if(char === '(') {      return ++counter;    } else if(char === ')') {      return --counter;    }  else { //matched some other char      return counter;    }      }, 0); //<-- starting value of the counter}
isParensBalanced('(())') // 0 <-- balancedisParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balancedisParensBalanced(')(') // -1 <-- not balanced

2.4 Counting Duplicate Array Items (Converting Array → Object)

There are times when you want to count duplicate array items or convert an array into an object. You can use reduce for that.

In the below example, we want to count how many cars of each type exist and put this figure into an object.

var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
var carsObj = cars.reduce(function (obj, name) {    obj[name] = obj[name] ? ++obj[name] : 1;  return obj;}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }

There are plenty more things you can do using reduce, and I encourage you to read the examples listed on MDN here.

3. Object destructuring

3.1 Removing unwanted properties

There are times when you want to remove unwanted properties — maybe because they contain sensitive info or are just too big. Instead of iterating over the whole object to removing them, we can simply extract such props to variables and keep the useful ones in the *rest* parameter.

In the below example, we want to remove _internal and tooBig properties. We can assign them to_internal and tooBig variables and store the remaining in a *rest* parameter cleanObject that we can use for later.

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}

3.2 Destructure nested objects in function params

In the below example, the engine property is a nested-object of the car object. If we are interested in, say, the vin property of engine, we can easily destructure it as shown below.

var car = {  model: 'bmw 2018',  engine: {    v6: true,    turbo: true,    vin: 12345  }}
const modelAndVIN = ({model, engine: {vin}}) => {  console.log(`model: ${model} vin: ${vin}`);}
modelAndVIN(car); // =&gt; model: bmw 2018  vin: 12345

3.3 Merge objects

ES6 comes with a spread operator (denoted by three dots). It is typically used to deconstruct array values, but you can use it on Objects as well.

In the following example, we use the spread operator to spread within a new object. Property keys in the 2nd object will override property keys in the 1st object.

In the below example, property keys b and c from object2override those from object1

let object1 = { a:1, b:2,c:3 }let object2 = { b:30, c:40, d:50}let merged = {…object1, …object2} //spread and re-add into mergedconsole.log(merged) // {a:1, b:30, c:40, d:50}

4. Sets

4.1 De-duping Arrays Using Sets

In ES6 you can easily de-dupe items using Sets, as Sets only allows unique values to be stored.

let arr = [1, 1, 2, 2, 3, 3];let deduped = [...new Set(arr)] // [1, 2, 3]

4.2 Using Array methods

Converting Sets to an Array is as simple as using a spread operator ( ). You can use all the Array methods easily on Sets as well!

Let’s say we have a set as shown below and we want to filter it to only contain items greater than 3.

let mySet = new Set([1,2, 3, 4, 5]);
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]

5. Array destructuring

Many times your function may return multiple values in an array. We can easily grab them by using Array destructuring.

5.1 Swap values

let param1 = 1;let param2 = 2;
//swap and assign param1 & param2 each others values[param1, param2] = [param2, param1];
console.log(param1) // 2console.log(param2) // 1

5.2 Receive and assign multiple values from a function

In the below example, we are fetching a post at /post and related comments at /comments . Since we are using async / await , the function returns the result in an array. Using array destructuring, we can simply assign the result directly into corresponding variables.

async function getFullPost(){  return await Promise.all([    fetch('/post'),    fetch('/comments')  ]);}
const [post, comments] = getFullPost();

If this was useful, please click the clap 👏 button down below a few times to show your support! ⬇⬇⬇ 🙏🏼

https://medium.com/@rajaraodv/latest

ECMAScript 2015+

  1. Examples of everything *NEW* in ECMAScript 2016, 2017, and 2018
  2. Check out these useful ECMAScript 2015 (ES6) tips and tricks
  3. 5 JavaScript “Bad” Parts That Are Fixed In ES6
  4. Is “Class” In ES6 The New “Bad” Part?

Terminal Improvements

  1. How to Jazz Up Your Terminal — A Step By Step Guide With Pictures
  2. Jazz Up Your “ZSH” Terminal In Seven Steps — A Visual Guide

WWW

  1. A Fascinating And Messy History Of The Web And JavaScript

Virtual DOM

  1. Inner Workings Of The Virtual DOM

React Performance

  1. Two Quick Ways To Reduce React App’s Size In Production
  2. Using Preact Instead Of React

Functional Programming

  1. JavaScript Is Turing Complete — Explained
  2. Functional Programming In JS — With Practical Examples (Part 1)
  3. Functional Programming In JS — With Practical Examples (Part 2)
  4. Why Redux Need Reducers To Be “Pure Functions”

WebPack

  1. Webpack — The Confusing Parts
  2. Webpack & Hot Module Replacement [HMR] (under-the-hood)
  3. Webpack’s HMR And React-Hot-Loader — The Missing Manual

Draft.js

  1. Why Draft.js And Why You Should Contribute
  2. How Draft.js Represents Rich Text Data

React And Redux :

  1. Step by Step Guide To Building React Redux Apps
  2. A Guide For Building A React Redux CRUD App (3-page app)
  3. Using Middlewares In React Redux Apps
  4. Adding A Robust Form Validation To React Redux Apps
  5. Securing React Redux Apps With JWT Tokens
  6. Handling Transactional Emails In React Redux Apps
  7. The Anatomy Of A React Redux App
  8. Why Redux Need Reducers To Be “Pure Functions”
  9. Two Quick Ways To Reduce React App’s Size In Production