Table of Contents
Object.fromEntries method
Object.fromEntries method support situation
Array.prototype.flat method
Array.prototype.flat method support situation
Array.prototype.flatMap method
Array.prototype.flatMap method support situation
String.trimStart and String.trimEnd methods
String.trimStart and String.trimEnd methods support situation
Optional catch binding
Support for optional catch binding
Changes to Function.toString() method
Support of Function.toString() method
Home Web Front-end CSS Tutorial All the New ES2019 Tips and Tricks

All the New ES2019 Tips and Tricks

Apr 18, 2025 am 10:19 AM

All the New ES2019 Tips and Tricks

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 ]
// ]
Copy after login

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 }
Copy after login

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 }
Copy after login

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!
Copy after login

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
Copy after login

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'
// ]
Copy after login

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'
// ]
Copy after login

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'
// ]
Copy after login

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
// ]
Copy after login

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
// ]
Copy after login

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
// ]
Copy after login

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 ]
// ]
Copy after login

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'
Copy after login

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'
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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}'
Copy after login

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'  
// '}'
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

How to Use CSS Grid for Sticky Headers and Footers How to Use CSS Grid for Sticky Headers and Footers Apr 02, 2025 pm 06:29 PM

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there's a bit of a learning curve, but Grid is

See all articles