I know that below are the two ways in JavaScript to check whether a variable is not null
, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
==) operator to check if a variable is not null, e.g. myVar !== null . The strict inequality operator will return true if the variable is not equal to null and false otherwise. Copied!
Use the is not operator to check if a variable is not Null in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
Javascript null is a primitive type that has one value null. JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.
The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
They are not equivalent. The first will execute the block following the if
statement if myVar
is truthy (i.e. evaluates to true
in a conditional), while the second will execute the block if myVar
is any value other than null
.
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
null
undefined
0
""
(the empty string)false
NaN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With