New ES2019 JavaScript features every developer should be excited about
Tags: javascript, webdev
Published: 2019-09-26 15:18:58

---
title: New ES2019 JavaScript features every developer should be excited about
published: true
tags: javascript, webdev
canonical_url: https://blog.logrocket.com/new-es2019-javascript-features-every-developer-should-be-excited-about/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/wwyyu67c7vzfwmo6rco6.png
---
**Written by [Gbolahan Olagunju](https://blog.logrocket.com/author/iamgbols/)**✏️

JavaScript has come a long way since its early days, with many new additions and features designed specifically to make the language more user-friendly and less verbose. Below are some recent additions to JavaScript that I find fascinating.

Some of these features are already available in Node, Chrome, Firefox, and Safari, while others are still in the proposal stage.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

### Optional chaining

Optional chaining is done using the `?.` operator. It primarily ensures that the preceding value before the question mark is neither undefined nor null. This is really useful when assessing the properties of deeply nested objects.

There’s a need to be sure that the `?.` operator exists before assessing the properties.

Consider the following example:

```jsx
const users = [
  {
   name: "Olagunju Gbolahan",
   occupation: "Software Developer",
   sayName(){
    console.log(`my name is ${this.name}`);
   },
   address: { office: "New York" }
  },
  { name: "Olawaseyi Moses" },
  { name: "Tunde Ednut" }
];
```

Let’s consider the second user in the array of users:

```jsx
const secondUser = users[1];
```

We may want to get the office address of this user. Before the advent of the optional chaining operator, we would have to go through a relatively inefficient process to obtain this information:

```jsx
const theAddress = secondUser.address && secondUser.address.office;
console.log(theAddress); // undefined
```

If we had a deeply nested object, we would have to check that its value existed using `&&` operator on each level.

But with the optional chaining, we simply do the following:

```jsx
const theAddress = secondUser?.address?.office;
console.log(theAddress); // undefined
```

We can also use optional chaining with object methods to confirm they exist before execution:

```jsx
const firstUser = users[0];
console.log(firstUser.sayName?.()); // my name is Olagunju Gbolahan
```

It will simply return `undefined` if a method with the given name doesn’t exist on the object.

```jsx
console.log(firstUser.sayOccupation?.()); // undefined
```

Because the optional chaining operator hasn’t been added to the JavaScript specification yet, it is still in the [proposal stage](https://github.com/tc39/proposal-optional-chaining).

You can use it today with the [babel-plugin-proposal-optional-chaining](https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining) plugin.

### Optional catch binding

This feature comes in handy when we know beforehand what our error will be, and we don’t want the redundancy of unused variables.

Consider the traditional try and catch block:

```jsx
try {
  const parsedJsonData = JSON.parse(obj);
} catch (error) {
  //the variable error has to be declared weather used or unused
  console.log(obj);
}
```

But with the addition of optional catch binding, we don’t have to provide unused variables — especially when we have defaults for our try block.

```jsx
function getName () {
  let name = "Gbolahan Olagunju";
  try {
    name = obj.details.name
  } catch {}
  console.log(name);
}
```

### The pipeline operator

This is one of the proposed additions to Javascript and it is currently at stage 1.

It essentially helps make several function calls to the same argument readable.

It does this by piping the value of an expression as argument(s) to a function. Consider calling the following functions without the pipeline operator `|>`.
```jsx
const capitalize = (input) =>  input[0].toUpperCase() + input.substring(1);
const removeSpaces = (input) => input.trim();
const repeat = (input) => `${input}, ${input}`;
```
```jsx
const withoutpipe = repeat(capitalize(removeSpaces('    i am gbols    ')));
console.log(withoutpipe); // I am gbols, I am gbols
```
But with the pipeline operator, readability can be greatly improved:

```jsx
const withpipe = '    i am gbols    '
                |> removeSpaces
                |> capitalize
                |> repeat;
console.log(withpipe); // // I am gbols, I am gbols
```

### String.trimStart and String.trimEnd

This was formally named trimRight and trimLeft, but with ES2019 the names were changed to the aliases trimStart and trimEnd to make them more intuitive to users.

Consider the following example:

```jsx
let massage = "     Welcome to LogRocket      ";
message.trimStart(); // "Welcome to LogRocket      "
message.trimEnd(); // "Welcome to LogRocket";
```

### Object.fromEntries

Before talking about Object.fromEntries, it is important to talk about Object.entries.

The Object.entries method was added to the ES2017 specification to provide a way to convert an object into its array equivalent, thus granting it access to all array methods for processing.

Consider the following object:

```jsx
const devs = {
  gbols: 5,
  andrew: 3,
  kelani: 10,
  dafe: 8,
};
const arrOfDevs = Object.entries(devs);
console.log(arrOfDevs);
//[
//  ["gbols", 5]
//  ["andrew", 3]
//  ["kelani", 10]
//  ["dafe", 8]
//]
```

Now, we can use the `filter` method on arrays to get devs that have more than 5 years experience:

```jsx
const expDevs = arrOfDevs.filter(([name, yrsOfExp]) => yrsOfExp > 5);
console.log(expDevs);
//[
//  ["kelani", 10]
//  ["dafe", 8]
//]
```

Then a problem arises: there is no easy way to convert the results back into an object. Usually, we would write our own code to transform this back into an object:

```jsx
const expDevsObj = {};
for (let [name, yrsOfExp] of expDevs) {
expDevsObj[name] = yrsOfExp;
}
console.log(expDevsObj);
//{
 //dafe: 8
 //kelani: 10
//}
```

But with the introduction of Object.fromEntries, we can do this in one swipe:

```jsx
console.log(Object.fromEntries(expDevs));
//{
 //dafe: 8
 //kelani: 10
//}
```

### Flat and FlatMap

Oftentimes, we have deeply nested arrays to deal with as a result of an API call. In this case, it’s especially important to flatten the array.

Consider the following example:
```jsx
const developers = [
  {
    name: 'Gbolahan Olagunju',
    yrsOfExp: 6,
    stacks: ['Javascript', 'NodeJs', ['ReactJs', ['ExpressJs', 'PostgresSql']]]
  },
  {
    name: 'Daniel Show',
    yrsOfExp: 2,
    stacks: ['Ruby', 'Jest', ['Rails', ['JQuery', 'MySql']]]
  },
  {
    name: 'Edafe Emunotor',
    yrsOfExp: 9,
    stacks: ['PHP', 'Lumen', ['Angular', 'NgRx']]
  }
];
```
```jsx
const allStacks = developers.map(({stacks}) => stacks);
console.log(allStacks);
// [
// ['Javascript', 'NodeJs', ['ReactJs', ['ExpressJs', 'PostgresSql']]]
// ['Ruby', 'Jest', ['Rails', ['JQuery', 'MySql']]]
// ['PHP', 'Lumen', ['Angular', 'NgRx']]
// ]
```
The `allstacks` variable contains deeply nested arrays. To flatten this array, we can use the Array.prototype.flat.

Here’s how:

```jsx
const flatSingle = allStacks.flat();
console.log(flatSingle);
//[
// "JavaScript",
//  "NodeJs",
// ['ReactJs', ['ExpressJs', 'PostgresSql']]]
// "Ruby",
// "Jest",
// ['Rails', ['JQuery', 'MySql']]]
// "PHP",
// "Lumen"
// ["Angular", "NgRx"]
//]
```

We can deduce from the above that the array has been flattened one level deep, which is the default argument to array.prototype.flat.

We can pass an argument to the flat method to determine the degree to which we want to flatten.

The defaults argument is a value of 1. To completely flatten the array, we can pass an argument of Infinity. The `Infinity` argument flattens the array completely, irrespective of the depth of the array.

Here’s how:

```jsx
const completelyFlat = allStacks.flat(Infinity);
console.log(completelyFlat);
//[
// "JavaScript",
// "NodeJs",
// "ReactJs",
// "ExpressJs",
// "PostgresSql",
// "Ruby",
// "Jest",
// "Rails",
// "JQuery",
// "MySql",
// "PHP",
// "Lumen",
// "Angular",
// "NgRx"
//]
```

### FlatMap

FlatMap is a combination of calling the map method and the flat method with a depth of 1. It is often quite useful as it does the same thing in a very efficient manner.

Below is a simple example of using both map and flatMap:
```jsx
let arr = ['my name is Gbols', ' ', 'and i am great developer']; 
console.log(arr.map(word => word.split(' ')));
//[
// ["my", "name", "is", "Gbols"],
// ["", ""],
// ["and", "i", "am", "great", "developer"]
//]
```
```jsx
console.log(arr.flatMap(word => word.split(' ')));
//[ "my"
//  "name"
//  "is"
//  "Gbols"
//   ""
//   ""
//   "and"
//   "i"
//   "am"
//   "great"
//   "developer"
//]
```
### Conclusion

In this article, we’ve counted the many benefits of new additions to JavaScript. These additions enhance the developer experience by reducing verbosity and increasing readability.

Below, check out a couple new features that we didn’t cover:  
[JSON.stringify](https://github.com/tc39/proposal-well-formed-stringify)  
[Sort stability](https://tc39.es/ecma262/#sec-array.prototype.sort)
* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/new-es2019-javascript-features-every-developer-should-be-excited-about/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [New ES2019 JavaScript features every developer should be excited about](https://blog.logrocket.com/new-es2019-javascript-features-every-developer-should-be-excited-about/) appeared first on [LogRocket Blog](https://blog.logrocket.com).