2022 has come to an end, and this year saw the release of the ES2022 spec which included lots of new features in Javascript. I wanted to take some time to
Array.findLast()
findLast
joins the commonly used map | reduce | filter
and friends of Array. The function makes it easy to find the last element of an Array that matches a given criteria.
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found); // 130
cause
fieldOftentimes, we catch an error returned by a downstream function and want to throw a more informative error. But if we overwrite the message on an Error
object, we lose the underlying cause of the error itself. So we have a better error message (+) that’s harder to debug (-).
The cause
field allows us to propagate errors upstream, giving us the best of both worlds: better error messages (+) that are easier to debug (+)
try {
connectToDatabase();
} catch (err) {
throw new Error('Connecting to database failed.', { cause: err });
}
Object.hasOwn()
If you’ve wanted to check if an object has a given property, you’ve probably reached for Object.hasOwnProperty()
However, this function doesn’t behave as expected in some scenarios, for example when using Object.create
to create a copy of an object.
This is just one example, read more in the ECMAScript Proposal:
const object1 = { hello: "world" };
console.log(object1.hasOwnProperty("hello")); // true
const object2 = Object.create(object1);
console.log(object2.hasOwnProperty("hello")); // false
// However:
object2.hasOwn("hello") // true
Match Indices are meant to provide a list of indices at which a given string matches a given regular expression. Prior to this proposal, regexp.match(string)
would return an index
field, but it would only correlate to the first index which matched the regular expression.
NOTE: For performance reasons, indices
will only be added to the result if the d
flag is specified.
const str = "foo bar foo";
const regexp = /foo/dg;
// The `indices` field is returned if the `d`
// modifier is present on the regex
console.log(regexp.exec(str).indices[0]); // [0, 3]
2022 was a big year for Javascript, but we have some even cooler stuff coming soon. Here are some of them which I’m particularly excited about! (You can track ECMAScript Proposals as proposals.es)