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)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
