Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is not null?

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) {...} 
like image 954
nickb Avatar asked Dec 05 '10 22:12

nickb


People also ask

How do you know if a value is not 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!

How do you check if a variable is not null in Python?

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).

How do you check if data is null?

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.

What is not null variable?

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.


1 Answers

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
like image 170
Tim Down Avatar answered Sep 28 '22 21:09

Tim Down