On April 14, Node.js (the server-side JavaScript Platform) version 14 was released, with various new capabilities, some of which are experimental, that potentially help API providers and consumers. Node.js is based on a Google-developed internal JavaScript engine named V8. V8 has released version 8.1, which incorporates several new features. Because this version is part of Node.js 14, those new features are also accessible in Node.js.
Take a closer look at some of the new capabilities that might assist Node.js development companies to streamline their development process.
Page Contents
Nullish Coalescing and Optional Chaining
Optional Chaining is a new JavaScript language feature in V8 version 8.1, and thus Node.js 14. Although seemingly insignificant, API users will greatly benefit from this capability. To grasp what it is, consider a scenario in which you could require it. When calling a Web API, you’ll either use an SDK designed specifically for the API (generally provided by the API provider) or an HTTP library like request.js (https://github.com/request/request). Some APIs offer a flexible response structure, which means that objects may or may not have the members you require.
For example, you could use the following API to get client information:
{
first: ‘John’,
last: ‘Smith’,
phone: ‘919-555-1212’,
office: {
primary: {
address: ‘123 Main St’,
city: ‘New York’,
state: ‘NY’,
zip: ‘10010’
},
secondary: {
address: ‘111 First Ave’,
city: ‘Chicago’,
state: ‘NY’,
zip: ‘60007’
}
}
}
This object contains an office object with two members: a primary and a secondary. If you need to access the zip of a secondary member, use the following code:
console.log(obj.office.secondary.zip);
This only works if all of the people you’re trying to contact are real. Assume that the API only provides a secondary object if the customer has a second location. If the entire secondary object has vanished, attempting to access its zip member will throw an exception because the secondary object is no longer present:
TypeError: Cannot read property ‘zip’ of undefined
Your entire Node.js software will crash if you don’t have an exception handler. Previously, you could get around this by using a lot of if statements in your code. There are several techniques, but this is the most straightforward:
if (obj && obj.office && obj.office.secondary && obj.office.secondary.zip) {
console.log(obj.office.secondary.zip);
}
else {
// Handle the situation that the secondary office isn’t present
}
However, with the updated version, you can use optional chaining with the V8 engine. Here’s how to put it to use:
console.log(obj.office.secondary?.zip);
There’s no need for a “if” statement. Please note the question mark behind the term secondary. This tells the node that you’re not sure if the office object will have a secondary object, and that if it doesn’t, the expression should be stopped and returned undefined. If the second object is present, the console.log will display the zip as follows:
60007
If the object isn’t present, the output will be undefined:
Undefined
Although an “if” statement will almost certainly be required, your code will be significantly simpler. You might need to use the question mark in numerous places in the expression, for example. Then you can try storing the zip in a variable and checking whether it contains undefined:
var zip = obj?.office?.secondary?.zip;
if (zip) {
console.log(`The secondary office zip is ${zip}.`);
}
else {
console.log(‘No secondary office zip code found.’);
}
The benefit of using a question mark after the initial obj is that you don’t have to check whether the request returned an object at all. Of course, you’ll still need to handle errors properly; for example, if the object returns null because the customer doesn’t exist, you’ll need a different error message than just stating that no secondary office zip code was detected. However, with fewer lines, your code will be simpler. Furthermore, fewer lines of code equal fewer defects.
The nullish coalescing operator is a new feature in V8 that works well with optional chaining. Prior to V8, you could use the logical “OR” operator to give a default value in an expression that would be used if a member didn’t exist, as in:
console.log(obj.value || “empty”);
Unless obj does not contain a valued member, in which case the term “empty” will be printed. There is, however, a fault here. This line of code will still output the phrase “empty” if obj. value is 0 or an empty string. That’s because the number 0, the empty string, the value null, and the value undefined all equal a false value in logical OR expressions.
Instead, the latest version of V8 introduces a new operator. It’s referred to as a nullish coalescing operator, and it’s made up of two question marks. It works essentially identically to the OR operator above, with the exception that only null and undefined values are passed through to the default value. So you can take advantage of it.
If the value is 0 or an empty string, you will receive the corresponding value, 0 or an empty string. The default value, in this example the phrase “empty,” is only returned if the value is null or undefined.
Return to the optional chaining functionality now. You can use the nullish coalescing operator to offer a default value, as in:
var custzip = obj.office.secondary?.zip ?? “No secondary zip code”;
console.log(custzip);
If the secondary object is existent and has a zip member, the zip code will be passed to the custzip variable. If either the secondary object or the zip member is missing, the expression to the left of?? will return undefined, which will be transformed into the string “No secondary zip code” by the??
Diagnostic Reports
Diagnostic Reports were an experimental feature in Node version 12. With this new version 14, that feature is no longer experimental and is now stable. That means you can use it in your production code right away.
A diagnostic report can be obtained with just one function call. Save the following code to a file, then run it with node:
function test() {
process.report.writeReport();
} test();
console.log(‘Ready’);
The single call, write a report, is inside the test function and stores the diagnostic report to a file. As you can see from the line Ready written to the console, the program is still running.
You’ll notice a new file with JSON after you execute this. When you open it, you’ll see a lot of information, including the version of Node that’s running, information about the computer, a full Stack trace for where the call to write report occurred in the code, full information on the JavaScript memory heap (much like Chrome’s debug tools), environment variables, and more.
This is just an overview of the subject, to learn more, you can check out in detail the Diagnostic reporting local storage in Node.js.
Conclusion
Node.js never fails to amaze developers with new versions and capture their interest with new features. A few of the exciting features that entice developers to learn more about include Nullish Coalescing, Optional Chaining, and Diagnostic reports local storage. You can use all these features in the production code right away and may be accessed through just a single function call.
Author Bio:
Kapil Panchal – Technical Content Manager
A passionate Technical writer and an SEO freak working as a Technical content manager in a reputed custom software development company. Having served in the Information technology, Services, and Product industry for years, I relish writing about technology and love sharing impeccable insights on various platforms. I believe in constant learning and am passionate about being better every day.