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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
