Since 2015, JavaScript has improved immensely.
It’s much more pleasant to use it now than ever.
In this article, we’ll look at the best features of ES2019.
Catch Binding
catch
binding is now optional with ES2019.
For instance, we can write:
let jsonData;
try {
jsonData = JSON.parse(str);
} catch {
jsonData = {};
}
Then we don’t need to get the thrown object in the parentheses after the catch
.
However, other kinds of errors that aren’t related to parsing will be silently ignored, since we just set it the jsonData
object to an empty object.
Another example would be to get a deeply nested property.
For instance, we can just write:
function logId(item) {
let id;
try {
id = item.data.id;
} catch {
console.log(id);
}
}
to let us safely get the deeply nested id
property of item
to id
if it exists.
If it doesn’t exist, then the code in the catch
block is run.
Stable Array.prototype.sort()
The Array.prototype.sort
method is now guaranteed to be stable.
So if something is considered to be the same when sorting, then they’ll stay in the same order in engines that supports ES2019.
If we have:
const arr = [{
key: 'foo',
value: 1
},
{
key: 'bar',
value: 2
},
{
key: 'foo',
value: 3
},
];
arr.sort((x, y) => x.key.localeCompare(y.key, 'en'));
Then arr
would be in the same order regardless of which environment it’s in.
JSON.stringify
JSON.stringify
can now take a lone surrogate.
So if we have:
JSON.stringify('u{D800}')
Then we get:
""ud800""
JSON superset
JSON strings now can have the '"u2028"'
character.
Function.prototype.toString Changes
Function.prototype.toString
now has some changes since ES2019.
The functions we defined returns a string with the original source code.
If we call toString
with a built-in function, then we see [native code]
.
For instance, if we have:
isNaN.toString()
Then we get:
"function isNaN() { [native code] }"
Functions created dynamically with the Function
and GeneratorFunction
engines must create the appropriate source code and attach it to functions.
All other cases would throw a type error.
Conclusion
Catch binding, function toString
, sort
methods all have changes with ES2019.