Abstract
- Handles situations where we try to access non-existent resources gracefully
- For example, it prevents issues like Segmentation Fault by shifting error detection from runtime to compile-time
Optional
Datatype
- A special datatype designed to achieve null safety
- The
Optional
datatype can either contain a value or be empty - When a programmer writing his/her codes, the Compiler will only compile if he/she handles the
Optional
explicitly - This feature is supported only in languages that provide both Generics and Compilation capabilities
Example
Safe Navigation
- Also known as Optional Chaining
- Provides a safe way to interact with potentially null or undefined values at runtime. When a
null
orundefined
is encountered, the program short-circuits and safely returnsundefined
instead of throwing an error.
Example
In Node.js, you can place a
?
(optional chaining operator) after a variable or property before accessing its value. If the variable or property isnull
orundefined
, it will returnundefined
instead of causing the program to crash.
Tip
When writing code, programmers can use Code Quality Assurance Tools such as Linters to identify code patterns that might lead to unexpected
undefined
values and ensure better code quality.