Use explicit null/undefined checks instead of truthy/falsy checks when handling potentially null or undefined values. Relying on truthy/falsy checks can lead to bugs when dealing with valid falsy values like 0 or empty strings.
Use explicit null/undefined checks instead of truthy/falsy checks when handling potentially null or undefined values. Relying on truthy/falsy checks can lead to bugs when dealing with valid falsy values like 0 or empty strings.
Bad:
// May mishandle valid 0 values
if (curr.outputCost) {
total = total.plus(curr.outputCost);
}
// Could yield "undefined" string
const username = String(env.USERNAME);
Good:
// Explicitly checks for null/undefined
if (curr.outputCost != null) {
total = total.plus(curr.outputCost);
}
// Uses nullish coalescing for default
const username = env.USERNAME ?? "default";
When parsing JSON or handling unknown data:
Enter the URL of a public GitHub repository