i am trying to check a state variable for null or empty or undefined at once
as per this post so link i have used !! to check for null or undefined but it is not working in my below code.
const [fleetOwner, setFleetOwner] = useState({id:'', name: ''});
if (!!fleetOwner && fleetOwner.id === undefined || fleetOwner.id === '') {
but getting error
×
TypeError: Cannot read properties of null (reading ‘id’)
which means !! not checking for null or undefined, tried with one !, and not working either. do we have syntax to check for all null or empty or undefined at once?
5
Answers
!! double bang operator converts any truthy/falsy value to an explicit true or false
Falsy values are (0, "",”,“, null, undefined, NaN) and truthy values are anything beside previously mentioned ones
however it’s not needed in this context since you want to check if you have falsy value
use !fleetOwner.id directly so it can equate to
if fleetOwner.id has a falsy value
also I’ve added checking that the propery do exist before accessing it using
Object.hasOwn static method so you won’t be getting the same error
I think you are missing a set of parentheses:
Not sure this is what you want to do but in your piece of code, the
fleetOwner.id === ''
is evaluated because of the||
As the error says, you can’t check a property of something that is null or undefined. Therefore you need to have a fallback condition to check if fleetOwner is NOT null or undefined before checking a property of fleetOwner.
There are several ways to acieve this.
In the code below there’s a fleetOwner check, and the machine will read from left to writte and the check
fleetOwner.id === ''
is only performed iffleetOwner
is not falsy:In the code below, the
?
checks if the variable exists before checking:check if a state variable is null, undefined, or empty, use the logical OR (||) operator along with nullish coalescing operator (??)
There are already a few solutions above, but here’s the reason for the error: operator precedence. The
&&
has higher priority than||
, thereforep && q || r
is evaluated as(p && q) || r
.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence
And yes, one solution would be to put parentheses to enforce the evaluation you want, so
p && (q || r)
.