How do I check for null values in JavaScript?
JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""
), null
, undefined
, false
and the numbers 0
and NaN
.
Please note that if you are specifically checking for numbers, it is a common mistake to miss 0
with this method, and num !== 0
is preferred (or num !== -1
or ~num
(hacky code that also checks against -1
)) for functions that return -1
, e.g. indexOf
).
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
will evaluate to true
if value
is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specification at the ToBoolean
section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
How to check for an undefined or null variable in JavaScript?
You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:value = obj.prop || defaultValue
which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue
JavaScript null check
An “undefined variable” is different from the value undefined
.
An undefined variable:
var a;
alert(b); // ReferenceError: b is not defined
A variable with the value undefined
:
var a;
alert(a); // Alerts “undefined”
When a function takes an argument, that argument is always declared even if its value is undefined
, and so there won’t be any error. You are right about != null
followed by !== undefined
being useless, though.
How can I determine if a variable is 'undefined' or 'null'?
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
.
How to check if a value is not null and not empty string in JS
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==
|===
).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false
).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if
. But, on the second one, every true-ish value will enter the if
: false
, 0
, null
, undefined
and empty strings, would not.
Related Topics
How to Combine Jquery Animate with CSS3 Properties Without Using CSS Transitions
Using JavaScript to Increment Top/Left/Bottom/Right Values
Ckeditor: Class or Id for Editor Body
Restart a Gif Animation Without Reloading the File
Why Does Reflow Need to Be Triggered for CSS Transitions
Get All Computed Style of an Element
Extract the Current Dom and Print It as a String, with Styles Intact
Change Svg Fill Color in :Before or :After CSS
How to Dynamically Remove a Stylesheet from the Current Page
Converting Em to Px in JavaScript (And Getting Default Font Size)
Creating a CSS Class in Jquery
Jquery-Ui Datepicker Change Z-Index
Detecting by How Much User Has Scrolled
How to Detect CSS Flex Wrap Event
Change CSS Rule in Class Using Jquery