What's New in JavaScript in 2024
The ECMA262 folks got together and we have the new JavaScript specification fresh out of the oven.
The 127th committee member meeting happened on June 26, 2024 and now we have a lot of cool stuff to look at this year! So let’s go through all the main features!
Synchronous Grouping in Maps and Objects#
Very similar to another proposal we talked about here, now we have a new method in Map and Object, the groupBy. What it does is allow us to group array items following a function. When used in a map, it gives us a map back, but we can use it in an object too.
Map.groupBy([1,2,3,4,5,6], (v) => v % 2 === 0 ? 'par' : 'impar')// Map(2) { 'par' => [2,4,6], 'impar' => [1,3,5] }The same way in an object:
Object.groupBy([1,2,3,4,5,6], (v) => v % 2 === 0 ? 'par' : 'impar')// { par: [ 1, 3, 5 ], impar: [ 2, 4, 6 ] }Promise.withResolvers#
This is another way we can define a Promise so we can resolve it outside its scope. The withResolvers method returns an object with the promise constructor, as well as the resolve and reject functions:
const { promise, resolve, reject } = Promise.withResolvers()The promise in question represents some kind of asynchronous work, while the two resolvers are decoupled from the promise itself. This is equivalent to something like:
let resolve, rejectconst p = new Promise((res, rej) => { resolve = res reject = rej})So we can do something like:
const { promise, resolve, reject } = Promise.withResolvers()resolve('resolvido')const res = await promise // res = 'resolvido'Overall, the use for this kind of thing is quite specific, it would be more when you want total control of the promise, or call the resolution methods from outside the promise, for example in streams or events.
Here we have an interesting explanation about this method with some examples.
The /v Flag in Regex#
The /v flag enables comparison in unicode sets, for example, emojis that have more than one code-point, which before couldn’t be compared like this:
/^\p{Emoji}$/u.test('😵💫') // falseThis doesn’t happen with this code:
/^\p{Emoji}$/u.test('🤯') // trueBecause 😵💫 has three code-points (it’s the combination of 😵 and 💫) and 🤯 has only one. But this can be solved with this code:
/^\p{RGI_Emoji}$/v.test('😵💫') // trueThis link has an extensive list of options and explanations about what is what in the unicode world.
ArrayBuffers and SharedArrayBuffers Got Updates#
The update is that, now, both can be resized without needing to be recreated:
const buffer = new ArrayBuffer(2, {maxByteLength: 4})const UIArr = new Uint8Array(buffer, 2) // starting at position 2UIArr.length // 0 because we have two empty positions
buffer.resize(4) // we fill the positionUIArr.length // 2Other Changes#
- String gained two methods
isWellFormedandtoWellFormedfor strings that represent references to UTF-16 Atomics.waitAsyncis a new method that allows us to wait asynchronously for a change in memory.