Check if value is false, true or null

Viewed 816

I want to check if variable is false, true or null. If null or undefined assign array to the variable by default. In other languages this syntax would be just fine to use. In js however when value is false then it assign array to myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)

I managed to do it with this syntax where I only check for null value

const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);

Is there any better way to do it in js?

2 Answers

Nullish coalescing.

Checks if a variable is either null or undefined and assign it to a default value if it's the case. 0 or false are not considered as nullish and will be assigned to the value.

The nullish coalescing operator ?? acts very similar to the || operator, except that we don’t use “truthy” when evaluating the operator. Instead we use the definition of nullish, meaning “is the value strictly equal to null or undefined?”

let a = null;

let b = a ?? "test";

console.log(b);

Example with false

let a = false;

let b = a ?? "test";

console.log(b);

There is an alternative to the other answer that ensures backwards compatibility (it's supported even by IE6) because it doesn't make use of the nullish coalescing operator. It's more verbose but also more convenient and accessible if you aren't using babel. Hope it helps!

const boolFromBody = null;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = undefined;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = false;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

Related