HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do I check for null values in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcheckforvaluesjavascriptnull

Problem

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;
}

Solution

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

Code Snippets

if(!pass || !cpass || !email || !cemail || !user){

Context

Stack Overflow Q#6003884, score: 1094

Revisions (0)

No revisions yet.