Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for null values in JavaScript?

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?

like image 751
Mahdi_Nine Avatar asked May 14 '11 18:05

Mahdi_Nine


People also ask

How do you check for null in JavaScript?

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.

IS null == in JavaScript?

In JavaScript, == compares values by performing type conversion. Both null and undefined return false. Hence, null and undefined are considered equal.

Is there an isNull function in JavaScript?

There is no isNull function in JavaScript script to find without value objects. However you can build your own isNull() function with some logics.


1 Answers

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

like image 150
Nobody Avatar answered Sep 20 '22 12:09

Nobody