-1
function test(val) {
    const hasError = val ?? true;
    if (hasError) {
        //error handling...
    } else {
        //do something...
    }
}
test(null) //error handling...
test(undefined) //error handling...
test('text') //error handling...
test(true) //error handling...

like this case i want to filter 'null' and 'undefined'

but it`s work every truthy value.

So i have only one option...

const hasError = (val === undefined || val === null);

Is there any way of use nullish operator in this case?

and when nullish operator is used generally?

thank you

Geewoo94
  • 11
  • 1
  • 1
    `val == null` is also true for `undefined` – Pointy Aug 30 '20 at 12:10
  • 1
    What do you mean by *"but it's work every truthy value"*? `0 ?? true` is `0`, not `true`. – T.J. Crowder Aug 30 '20 at 12:11
  • Looking at your code, I would tend to assume you'd want `= val ?? false`, not `= val ?? true`. (Or `val == null` as @Pointy pointed out.) `= val ?? true` means that if `val` is `null` or `undefined`, `hasError` will get the value `true`, and if `val` is anything else (like `"text"` or `true` or `42`), `hasError` will get that value (`"text"` or `true` or `42`). What values of `val` should mean `hasError` is true? – T.J. Crowder Aug 30 '20 at 12:14

1 Answers1

0

If you're sure that

const hasError = (val === undefined || val === null);

captures the logic you want, then the problem is that

const hasError = val ?? true;

gives you the opposite of that if you're subsequently going to use that flag in an if expression. You'd really want to follow with

if (hasError !== true)

which is really confusing (to me). Instead, you can think of the ?? operator giving you the opposite:

const noError = val ?? true;
if (!noError) 

which makes a little more sense. Personally I'd use

const hasError = val == null;

or just perform the test in the if directly.

Pointy
  • 405,095
  • 59
  • 585
  • 614