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
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 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
).
Checking for null or undefined
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
No, it gets the job done 100% of the time. The only values that are == null
are null
and undefined.
0 == null
is false. "" == undefined
is false. false == null
is false. Etc. You're confusing == null
with falsiness, which is a very different thing.
That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null
or the explicit one you're currently using (or if (value === undefined || value === null)
) is a matter of style and in-house convention. But value == null
does do what you've asked: Checks that value
is null
or undefined
.
The details of ==
are here: Abstract Equality Comparison.
How do I check for an empty/undefined/null string in JavaScript?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against ""
using the ===
operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !==
operator:
if (strValue !== "") {
// strValue was not an empty string
}
How to check if a value is null or undefined in JavaScript (ES2020)
eslint
will not throw an error for value == null
if smart option is enabled
For project that doesn't have smart
eqeqeq
rule in eslint
config,
There's a shorter way of doing it with Nullish Coalescing.
(value ?? null) !== null
let value
// undefined
console.log((value ?? null) !== null)
// null
value = null
console.log((value ?? null) !== null)
// ''
value = ''
console.log((value ?? null) !== null)
// 0
value = 0
console.log((value ?? null) !== null)
// []
value = []
console.log((value ?? null) !== null)
Related Topics
How to Replace Plain Urls With Links
Innertext' Works in Ie, But Not in Firefox
Window.Onload VS Document.Onload
Using the Variable "Name" Doesn't Work With a Js Object
How May I Reference the Script Tag That Loaded the Currently-Executing Script
Convert String to Title Case With JavaScript
JavaScript Equivalent of Python'S Zip Function
How to Send a Cross-Domain Post Request Via JavaScript
When Should I Use Curly Braces For Es6 Import
How Does the "This" Keyword in JavaScript Act Within an Object Literal
Is JavaScript Guaranteed to Be Single-Threaded
What Does 'Return' Keyword Mean Inside 'Foreach' Function
Format Number to Always Show 2 Decimal Places
How to Distinguish Between Left and Right Mouse Click With Jquery