How can I check for null values in JavaScript? I wrote the code below but it didn't work.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
And how can I find errors in my JavaScript programs?
null
in js should be done with the strict operator ===
davin 2011-05-14 18:19
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
)
!
or !!
to test for null
or undefined
on typically-numeric data unless you also want to throw away values of 0 - NickS 2016-02-24 21:06
0
...". I believe this answer is perfectly appropriate for the question as given the context (which I'm inferring is "username, password, email"), they're not checking for 0
values. Given the popularity of this question and answer, however, I agree that it's worth mentioning in the answer itself - Mark Kahn 2016-06-24 20:13
To check for null SPECIFICALLY you would use this:
if(variable === null && typeof variable === "object")
...or more simply:
if(variable === null)
This test will ONLY pass for null
and will not pass for ""
, undefined
, false
, 0
, or NaN
.
The rest of this is in response to inorganik's comment, Yes, you can check each one individually.
You need to implement use of the absolutely equals: ===
and typeof
to be absolutely sure with your checks.
I've created a JSFiddle here to show all of the individual tests working
Here is all of the output of the tests:
Null Test:
if(variable === null && typeof variable === "object")
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if(variable === "" && typeof variable === "string")
- variable = ""; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if(variable === undefined && typeof variable === "undefined")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if(variable === false && typeof variable === "boolean")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if(variable === 0 && typeof variable === "number")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if(!parseFloat(variable) && variable != 0 && typeof variable === "number")
- variable = ""; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
As you can see, it's a little more difficult to test against NaN
;
===
strict equality? Thanks.
Also for NaN test you can use isNaN(value)
that will return true
only if variable equals NaN - Michael Malinovskij 2015-02-11 13:20
absolutely equals
and not received a proper value in return with checking typeof
. lol. Also, I've had some issues with isNaN
in the past, so I decided to provide what is an absolutely sure-fire way to check each one. There should be no case failure on any of these checks. You're welcome - WebWanderer 2015-02-11 18:10
variable === null
but is not of type "object"? If there is not, why not simplify the check to variable === null
, throwing out the second conjunct? Thanks - Hunan Rostomyan 2015-04-04 22:19
variable === null
which I just tested here in this JSFiddle. The reason I also used && typeof variable === 'object'
was not only to illustrate the interesting fact that a null
value is a typeof object
, but also to keep with the flow of the other checks. But yes, in conclusion, you are safe to use simply variable === null
- WebWanderer 2015-04-06 14:59
just replace the ==
with ===
in all places.
==
is a loose or abstract equality comparison
===
is a strict equality comparison
See the MDN article on Equality comparisons and sameness for more detail.
undefined
to be not null
. Otherwise it will lead to a lot of unexpected behavior. Generally if you're interested in both null
/undefined
but not falsy values, then use ==
(one of the few cases when you should do so) - Andrew Mao 2016-05-11 22:40
undefined
is not null
: http://stackoverflow.com/a/5076962/75323 - ic3b3rg 2016-06-27 02:18
Strict equality operator:-
We can check null by ===
if ( value === null ){
}
Just by using if
if( value ) {
}
will evaluate to true if value is not:
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
A cleaner way to do your check would be to simply use the ! operator:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
Improvement over the accepted answer by explicitly checking for null
but with a simplified syntax:
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
}
// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
console.log ("Yayy! None of them are null");
} else {
console.log ("Oops! At-lease one of them is null");
}
you can use try catch finally
try {
document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
} catch (e) {
if (e.name.toString() == "TypeError") //evals to true in this case
//do something
} finally {}
you can also throw
your own errors. See this.
to check for undefined and null in javascript you need just to write the following :
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
but this will fail for rational numbers which would round to 0
, such as variable = 0.1
. A better test would be:
if(isNaN(variable) && typeof variable === "number")
parseInt
to parseFloat
(which should have been obvious to me in the first place). I avoided using the isNan
function because I feel as if many developers view functions such as isNaN
as some sort of "magic box" that values go into and booleans come out of, and I wanted to should the test a little more in depth. But yes, your suggested test will work and is perfectly fine to use. Sorry I didn't notice your post until now - WebWanderer 2015-04-16 15:06
isNaN
as well, I can get behind that logic. There's also the Underscore.js method, which seems even more confusing/blackbox, but worth noting anyway because it takes advantage of NaN !== NaN
.
Object.prototype.toString.call(variable) === '[object Number]' && variable !== +variable
Gabriel 2015-04-18 00:23
In JavaScript, no string is equal to null
.
Maybe you expected pass == null
to be true when pass
is an empty string because you're aware that the loose equality operator ==
performs certain kinds of type coercion.
For example, this expression is true:
'' == 0
In contrast, the strict equality operator ===
says that this is false:
'' === 0
Given that ''
and 0
are loosely equal, you might reasonably conjecture that ''
and null
are loosely equal. However, they are not.
This expression is false:
'' == null
The result of comparing any string to null
is false. Therefore, pass == null
and all your other tests are always false, and the user never gets the alert.
To fix your code, compare each value to the empty string:
pass === ''
If you're certain that pass
is a string, pass == ''
will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.
If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.
Actually I think you may need to use
if (value !== null || value !== undefined)
because if you use if (value)
you may also filter 0 or false values.
Consider these two functions:
const firstTest = value => {
if (value) {
console.log('passed');
} else {
console.log('failed');
}
}
const secondTest = value => {
if (value !== null && value !== undefined) {
console.log('passed');
} else {
console.log('failed');
}
}
firstTest(0); // result: failed
secondTest(0); // result: passed
firstTest(false); // result: failed
secondTest(false); // result: passed
firstTest(''); // result: failed
secondTest(''); // result: passed
firstTest(null); // result: failed
secondTest(null); // result: failed
firstTest(undefined); // result: failed
secondTest(undefined); // result: failed
In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0
or false
or ''
values. so I used the second test, but you may need to filter them too which may cause you to use first test.
Please view carefully before downvote.
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined
. so we can check variable even if it would be an object
holding some instance in place of value.
create a helper method for checking nullity that returns true
and use it in your API.
helper function to check if variable is empty:
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch exceptional API call:
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
some test cases:
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));
This will not work in case of Boolean values coming from DB for ex:
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
Try this:
if (!variable && typeof variable === "object") {
// variable is null
}
if (variable === null)
? Also someone already provided that answer last year: http://stackoverflow.com/a/27550756/218196 - Felix Kling 2015-11-03 14:44