Explorer
Node.js

Write a function `getValueOrDefault(val, defaultVal)` that returns `val` if it is NOT null/undefined, otherwise returns `defaultVal`. Note: `0`, `""`, and `false` should NOT trigger the default.

Problem Statement

Write a function `getValueOrDefault(val, defaultVal)` that returns `val` if it is NOT null/undefined, otherwise returns `defaultVal`. Note: `0`, `""`, and `false` should NOT trigger the default.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: The || operator treats 0, "", and false as falsy. You need something different. šŸ’” Hint 2: The nullish coalescing operator (??) only checks for null and undefined. šŸ’” Hint 3: return val ?? defaultVal; āœ… Solution: ```javascript function getValueOrDefault(val, defaultVal) { return val ?? defaultVal; } ```

Nullish Coalescing (??)

Easy
Write a function `getValueOrDefault(val, defaultVal)` that returns `val` if it is NOT null/undefined, otherwise returns `defaultVal`. Note: `0`, `""`, and `false` should NOT trigger the default.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["default",0,"",false,"default","hello"]