Posts

Showing posts with the label Null Coalescing Operator

Use of Null Coalescing Operator

Image
Null Coalescing Operator The new null coalescing operator (??) simplifies code with verbose null checks.  For example - Old Ways -  Example 1 -  Integer anInteger; // Assume this is passed as parameter and can be NULL  Integer notNullReturnValue; if (anInteger != null){   notNullReturnValue = anInteger; } else {   notNullReturnValue = 100; } Example 2 -  Integer notNullReturnValue = (anInteger != null) ? anInteger : 100; New Way (Null Coalescing Operator) - Integer anInteger; // Assume this is passed as parameter and can be NULL  Integer notNullReturnValue = anInteger ?? 100; Note : nullish coalescing operator (??) is also part of modern JavaScript APIs. You can also use them in your Lightning Web Components (LWCs) to simplify null checks. When using the null coalescing operator, always remember operator precedence. In some cases, using parentheses is necessary to obtain the desired results. For example, the expression top ?? 100 - bottom ?? 0 e...