3

I have the following pre-configuration

const preloadedConfig = {
  "configA": null, // either true, false or null is allowed
};

and then I have the following initialization on page load

let finalConfig = preloadedConfig.configA || true;

The scenario:

  1. Properties in the preloaded config can be changed to either true, false or null based on the user's preference

  2. I wish to use short-circuit evaluation to determine the user choice on page load. If no choice(null) is supplied by the user, default the choice to true

My issue:

Based on the following extracted from here:

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

The following is evaluated:

true >> evaluted true // ok
null >> evaluted true // ok
false >> evaluted true // the problem area

If the user supplies the config option of false, the final evaluated value will always result in true due to it being a "falsy value".

My desired outcome is a boolean value of false if the value supplied is false.

What should I do to make this work while using short-circuit evaluation and allowing 3 types of input values of null, true or false?

dian jin
  • 195
  • 3
  • 12

3 Answers3

3

You can use the nullish coalescing operator instead.

let finalConfig = preloadedConfig.configA ?? true;

Alternatively, you can use a hasOwnProperty check.

let finalConfig = preloadedConfig.hasOwnProperty('configA') ? preloadedConfig.configA : true;
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

In modern environments (or with a transpiler), I'd use the nullish coalescing operator, which takes the right side only if the left side is null or undefined:

let finalConfig = preloadedConfig.configA ?? true;

Otherwise, use the conditional operator:

let finalConfig = preloadedConfig.configA == null ? true : preloadedConfig.configA;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You can make defaulting rule a bit better by using old Object.assign or modern destruct ... prop.

This will override configA even with null

const yourConfig = {
    configA: true,
    ...preloadedConfig
}

With old env woudl be

Obejct.assign({configA: true},preloadedConfig)

EDIT:

Taking nulls as default would be

const yourConfig = {
    configA: true,
    ...Object.fromEntries(Object.entries(preloadedConfig).filter(([key,val])=>val!==null))
}
uke
  • 893
  • 4
  • 10