Where to use nullish operator in javascript?

104 views Asked by At
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

1

There are 1 answers

0
Pointy On

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.