Easy

Provide Default Values Using Nullish Coalescing Operator (??)

Description

In this challenge, you need to write a function that takes two arguments: a value and a default value.

The function should return the provided value if it is not null or undefined; otherwise, it should return the default value.

The nullish coalescing operator (??) in JavaScript is useful for providing default values when dealing with potentially null or undefined variables. Unlike the logical OR (||) operator, it only checks for null or undefined, not other falsy values such as 0 or an empty string.

Instructions

Write a function called getValueOrDefault that takes two parameters:

  • value: a value that may be null or undefined.
  • defaultValue: the fallback value to return if value is null or undefined.

The function should return value if it is not null or undefined, otherwise return defaultValue.

Example usage:

// Expected output: "Default"
getValueOrDefault(undefined, 42);
// Expected output: 42
getValueOrDefault(0, 100);
// Expected output: 0 (0 is not null or undefined)
getValueOrDefault("Hello", "Default");
// Expected output: "Hello"

window code 2Test Cases

Input:

null

Expected Output:

"Default"