What is the NC + OC Technique in JavaScript? and How to Use It
Elevating Code Safety and Readability through Nullish Coalescing and Optional Chaining

We are a Programming and Technology community. Somos una comunidad de Programación y Tecnología.
In the landscape of modern JavaScript development, handling deeply nested objects and unpredictable API responses has historically been a source of significant technical debt. Junior-level patterns often rely on verbose logical AND (&&) chains or nested if statements to verify the existence of every parent property before accessing a child value. However, senior developers utilize a more elegant, resilient pattern known as the NC + OC Technique.
By combining Nullish Coalescing (NC) and Optional Chaining (OC), you can write defensive code that is both safer and significantly more readable.
The Power of Optional Chaining (OC)
The ?. operator allows you to read the value of a property located deep within a chain of connected objects without having to manually validate that each reference in the chain is valid.
How it works: If any part of the chain—such as
user?.profile?.avatar—isnullorundefined, the expression short-circuits and returnsundefinedinstead of throwing aTypeError.Expert Value: This eliminates the "Cannot read property 'x' of undefined" errors that frequently crash production applications.
The Precision of Nullish Coalescing (NC)
The ?? operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined.
Beyond the Logical OR: Unlike the traditional
||operator, which triggers for any "falsy" value (like0,"", orfalse), the Nullish Coalescing operator only triggers for truly nullish values.Defining Defaults: In the example
user?.profile?.avatar ?? "photo.png", the default image is only assigned if the avatar property is strictly missing or null.
The Senior Developer Workflow
Traditional "long and error-prone" code often looks like this:
if (user && user.profile && user.profile.avatar) { return user.profile.avatar; } else { return "photo.png"; }
A senior developer refactors this into a single, declarative line:
const avatar = user?.profile?.avatar ?? "photo.png";
his refactor doesn't just save space; it makes the intent of the code immediately clear. It signals to other developers that the data structure is flexible and that the application is prepared to handle missing data gracefully.
Conclusion
The NC + OC technique is more than just "syntactic sugar"; it is a fundamental shift toward safer, more declarative JavaScript. By mastering these operators, you reduce boilerplate, prevent common runtime crashes, and ensure that your code remains clean and maintainable even when dealing with the most complex nested data structures.



