ES2019 brings several new features to the ECMAScript standard. These features are officially available in Node.js, Chrome, Firefox, and Safari. To support older browsers, you can also use Babel to compile these features into different versions of JavaScript.
Let's see what new features are available!
Object.fromEntries
method
ES2017 introduces the Object.entries
method, which converts objects into their array representations. For example:
let students = { amelia: 20, beatrice: 22, cece: 20, deirdre: 19, eloise: 21 } Object.entries(students) // [ // [ 'amelia', 20 ], // [ 'beatrice', 22 ], // [ 'cece', 20 ], // [ 'deirdre', 19 ], // [ 'eloise', 21 ] // ]
This is very useful because it allows objects to use a number of functions built into array prototypes such as map
, filter
, reduce
, etc. However, converting the result back to the object requires a relatively tedious process.
let students = { amelia: 20, beatrice: 22, cece: 20, deirdre: 19, eloise: 21 } // Convert to an array to use the .filter() function let overTwentyOne = Object.entries(students).filter(([name, age]) => { return age >= 21 }) // [ [ 'beatrice', 22 ], [ 'eloise', 21 ] ] // Convert multidimensional array back to object let DrinkingAgeStudents = {} for (let [name, age] of overTwentyOne) { DrinkingAgeStudents[name] = age; } // { beatrice: 22, eloise: 21 }
Object.fromEntries
method is designed to eliminate this loop! It provides cleaner code to facilitate you to use array prototype methods on objects.
let students = { amelia: 20, beatrice: 22, cece: 20, deirdre: 19, eloise: 21 } // Convert to an array to use the .filter() function let overTwentyOne = Object.entries(students).filter(([name, age]) => { return age >= 21 }) // [ [ 'beatrice', 22 ], [ 'eloise', 21 ] ] // Convert multidimensional array back to object let DrinkingAgeStudents = Object.fromEntries(overTwentyOne); // { beatrice: 22, eloise: 21 }
It should be noted that arrays and objects are different data structures, and converting between the two can lead to data loss. The following example shows how an array element becomes a duplicate object key:
let students = [ [ 'amelia', 22 ], [ 'beatrice', 22 ], [ 'eloise', 21], [ 'beatrice', 20 ] ] let studentObj = Object.fromEntries(students); // { amelia: 22, beatrice: 20, eloise: 21 } // The first beatrice was discarded!
Be aware of potential side effects when using these functions.
Object.fromEntries
method support situation
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 67 | 12.1 | Not supported |
Array.prototype.flat
method
Multidimensional arrays are a very common data structure, especially when retrieving data. The ability to flatten multidimensional arrays is necessary. Although it could have been done before, the method is not elegant.
Let's look at an example where map
function returns a multidimensional array that needs to be flattened.
let courses = [ { subject: "math", numberOfStudents: 3, waitlistStudents: 2, students: ['Janet', 'Martha', 'Bob', ['Phil', 'Candace']] }, { subject: "english", numberOfStudents: 2, students: ['Wilson', 'Taylor'] }, { subject: "history", numberOfStudents: 4, students: ['Edith', 'Jacob', 'Peter', 'Betty'] } ] let courseStudents = courses.map(course => course.students) // [ // [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ], // [ 'Wilson', 'Taylor' ], // [ 'Edith', 'Jacob', 'Peter', 'Betty' ] // ] [].concat.apply([], courseStudents) // We have to use this method
Array.prototype.flat
method came into being. It accepts an optional depth parameter.
let courseStudents = [ [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ], [ 'Wilson', 'Taylor' ], [ 'Edith', 'Jacob', 'Peter', 'Betty' ] ] let flattenOneLevel = courseStudents.flat(1) console.log(flattenOneLevel) // [ // 'Janet', // 'Martha', // 'Bob', // [ 'Phil', 'Candace' ], // 'Wilson', // 'Taylor', // 'Edith', // 'Jacob', // 'Peter', // 'Betty' // ] let flattenTwoLevels = courseStudents.flat(2) console.log(flattenTwoLevels) // [ // 'Janet', 'Martha', // 'Bob', 'Phil', // 'Candace', 'Wilson', // 'Taylor', 'Edith', // 'Jacob', 'Peter', // 'Betty' // ]
Note that if no parameters are specified, the default depth is 1. This is very important because in our example, this does not completely flatten the array.
let courseStudents = [ [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ], [ 'Wilson', 'Taylor' ], [ 'Edith', 'Jacob', 'Peter', 'Betty' ] ] let defaultFlattened = courseStudents.flat() console.log(defaultFlattened) // [ // 'Janet', // 'Martha', // 'Bob', // [ 'Phil', 'Candace' ], // 'Wilson', // 'Taylor', // 'Edith', // 'Jacob', // 'Peter', // 'Betty' // ]
The reason for this design is that the function is not greedy by default and requires explicit instructions to run in this way. Infinity
can be used as a parameter for cases where the depth is unknown and the intention is to completely flatten the array.
let courseStudents = [ [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ], [ 'Wilson', 'Taylor' ], [ 'Edith', 'Jacob', 'Peter', 'Betty' ] ] let alwaysFlattened = courseStudents.flat(Infinity) console.log(alwaysFlattened) // [ // 'Janet', 'Martha', // 'Bob', 'Phil', // 'Candace', 'Wilson', // 'Taylor', 'Edith', // 'Jacob', 'Peter', // 'Betty' // ]
As always, greedy operations should be used with caution, and if the depth of the array is indeed unknown, greedy operations may not be a good choice.
Array.prototype.flat
method support situation
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 67 | 12 | Not supported |
Chrome Android | Firefox Android | iOS Safari | IE Mobile | Samsung Internet | Android Webview |
---|---|---|---|---|---|
75 | 67 | 12.1 | Not supported | Not supported | 67 |
Array.prototype.flatMap
method
With the addition of the flat
method, we also get the combined function Array.prototype.flatMap
. We've actually seen what it works in the example above, but let's look at one more.
If we wanted to insert elements into an array, what would it look like before ES2019 add these features?
let grades = [78, 62, 80, 64] let curved = grades.map(grade => [grade, grade 7]) // [ [ 78, 85 ], [ 62, 69 ], [ 80, 87 ], [ 64, 71 ] ] let flatMapped = [].concat.apply([], curved) // Now flat, flat can be used but it did not exist before // [ // 78, 85, 62, 69, // 80, 87, 64, 71 // ]
Now that we have Array.prototype.flat
, we can improve this example a little bit.
let grades = [78, 62, 80, 64] let flatMapped = grades.map(grade => [grade, grade 7]).flat() // [ // 78, 85, 62, 69, // 80, 87, 64, 71 // ]
However, this is still a relatively popular pattern, especially in functional programming. So it's great to have it built into an array prototype. Using flatMap
we can do this:
let grades = [78, 62, 80, 64] let flatMapped = grades.flatMap(grade => [grade, grade 7]); // [ // 78, 85, 62, 69, // 80, 87, 64, 71 // ]
Remember, the default parameter for Array.prototype.flat
is 1. flatMap
is equivalent to combining map
and flat
without parameters. Therefore, flatMap
will only flatten one layer.
let grades = [78, 62, 80, 64] let flatMapped = grades.flatMap(grade => [grade, [grade 7]]); // [ // 78, [ 85 ], // 62, [ 69 ], // 80, [ 87 ], // 64, [ 71 ] // ]
Array.prototype.flatMap
method support situation
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 67 | 12 | Not supported |
Chrome Android | Firefox Android | iOS Safari | IE Mobile | Samsung Internet | Android Webview |
---|---|---|---|---|---|
75 | 67 | 12.1 | Not supported | Not supported | 67 |
String.trimStart
and String.trimEnd
methods
Another nice addition to ES2019 is the alias, which makes some string function names more explicit. Previously, String.trimRight
and String.trimLeft
were available.
let message = " Welcome to CS 101 " message.trimRight() // ' Welcome to CS 101' message.trimLeft() // 'Welcome to CS 101' message.trimRight().trimLeft() // 'Welcome to CS 101'
These are great functions, but it is also helpful to give them names that suit their purpose more. Delete the start and end spaces.
let message = " Welcome to CS 101 " message.trimEnd() // ' Welcome to CS 101' message.trimStart() // 'Welcome to CS 101' message.trimEnd().trimStart() // 'Welcome to CS 101'
String.trimStart
and String.trimEnd
methods support situation
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 67 | 12 | Not supported |
Optional catch
binding
Another nice feature of ES2019 is to make the parameters in try-catch
block optional. Previously, all catch
blocks passed exceptions as parameters. This means that even if the code in catch
block ignores it, it still exists.
try { let parsed = JSON.parse(obj) } catch(e) { // Ignore e, or use console.log(obj) }
This is not the case anymore. If no exception is used in catch
block, nothing is needed at all.
try { let parsed = JSON.parse(obj) } catch { console.log(obj) }
This is a good option if you already know what the error is and are looking for the data that triggers it.
Support for optional catch
binding
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 67 | 12 | Not supported |
Changes to Function.toString()
method
ES2019 also changed the way Function.toString()
method runs. Previously, it completely removed spaces.
function greeting() { const name = 'CSS Tricks' console.log(`hello from ${name}`) } greeting.toString() //'function greeting() {\nconst name = \'CSS Tricks\'\nconsole.log(`hello from ${name} //`)\n}'
Now it reflects the true representation of the function in the source code.
function greeting() { const name = 'CSS Tricks' console.log(`hello from ${name}`) } greeting.toString() // 'function greeting() {\n' // " const name = 'CSS Tricks'\n" // ' console.log(`hello from ${name}`)\n' // '}'
This is mainly an internal change, but I can’t help thinking that this may make life easier for a blogger or two in the future.
Support of Function.toString()
method
Chrome | Firefox | Safari | Edge |
---|---|---|---|
75 | 60 | 12 – Partial support | 17 – Partial support |
This is the main new feature of ES2019!
You may also want to explore some other new features, including:
- Symbol description
- Sorting stability
- ECMAScript as a superset of JSON
-
JSON.stringify
Have a happy JavaScript programming!
The above is the detailed content of All the New ES2019 Tips and Tricks. For more information, please follow other related articles on the PHP Chinese website!

Here's a container with some child elements:

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools