Html check if null

How to check if a variable is not null?

I know that below are the two ways in JavaScript to check whether a variable is not null , but I’m confused which is the best practice to use. Should I do:

10 Answers 10

They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null .

The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):

Here is how you can test if a variable is not NULL:

the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..

In case for those wondering. This does not check for an empty string («») and undefined. See my fiddle as reference: jsfiddle.net/b0tm7yaf

  • code inside your if(myVar) < code >will be NOT executed only when myVar is equal to: false, 0, «», null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) will be NOT executed only when myVar is equal to null or you never defined it (throws exception).
Читайте также:  Java find class reflection

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

It also mentions what’s considered ‘falsey’ that you might not realise.

This check is actually not safe. If myvar is 0, false or any other falsy value the test will fail (if you only intend to check for not null). So only use this to check for not null if the variable can never have another falsy value.

the link no longer works. I found a copy of what appears to be the post here: appendto.com/2010/10/… It’s strange though, because Elijah’s post (and the sample code) would suggest that he’s the author, but he’s not listed as the author there.

Looks like that site no longer exists. It would be helpful if you could include the information in the post itself, rather than just an external link.

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

So, null was a string which read «null» rather than really being null.

EDIT: It should be understood that I’m not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I’m not sure why. perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It’s frustrating to see this down-voted by someone who understands that it’s not quite right, and then up-voted by someone it actually helps.

Источник

How do I check for null values in JavaScript?

@cwolves, if I thought it were the problem I would have made that comment an answer. Check out my wording, I’m clearly making a general statement about the language in reference to the OP’s practise, and not proposing that this solves his problem.

@TRiG the proposed changes fundamentally alter the nature of the question to the point where the answers (not just mine) lose context and don’t make sense. The edit should just be a comment.

24 Answers 24

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

It would be very useful to know which parts of this test for which values. Sometimes you're looking for one in particular.

Somewhat of a late statement, but yes, you can perform test against each one @inorganik , see my answer below

Readers, please be careful when using this type of test on numeric data. Do not use ! or !! to test for null or undefined on typically-numeric data unless you also want to throw away values of 0.

The answer itself states this: ". and the numbers 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.

@zyklus Even if he is asking about usernames and passwords, it's possible that functions could be gathering the data from the forms and returning null if an empty string is found. But much more importantly, Stack Overflow questions come up as google results all the time, so many people who are curious how to check for a null value will be directed here and will see your answer first. It probably would have been best to answer the question that was asked and then address the specifics of this code. Sorry if that upsets you, SO asks me to comment when I downvote an answer so I am doing that.

To check for null SPECIFICALLY you would use this:

This test will ONLY pass for null and will not pass for "" , undefined , false , 0 , or NaN .

Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable ).

Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof .

Here is the output of each check:

Null Test: if (variable === null) - 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 === '') - 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 (typeof variable == "undefined") -- or -- if (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) - 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) - 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 (typeof variable == 'number' && !parseFloat(variable) && variable !== 0) -- or -- if (isNaN(variable)) - 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 ;

Источник

JavaScript check if value is only undefined, null or false

Other than creating a function, is there a shorter way to check if a value is undefined , null or false only in JavaScript? The below if statement is equivalent to if(val===null && val===undefined val===false) The code works fine, I'm looking for a shorter equivalent.

Above val==null evaluates to true both when val=undefined or val=null . I was thinking maybe using bitwise operators, or some other trickery.

I think this is the shortest you can get. or create your own function. Btw, '0' does not evaluate to false .

9 Answers 9

Well, you can always "give up" 🙂

@Konza: That just how == is defined. Its fairly complicated and its why many people recommend using === unless you really know what you are doing.

It's crazy but for me it doesn't worw with null but with 'null' !! And also not work with val == '' (tested both in firefox console and live. if you have a clue ?

I think what you're looking for is !!val==false which can be turned to !val (even shorter):

function checkValue(value) < console.log(!!value); >checkValue(); // false checkValue(null); // false checkValue(undefined); // false checkValue(false); // false checkValue(""); // false checkValue(true); // true checkValue(<>); // true checkValue("any string"); // true 

That works by flipping the value by using the ! operator.

If you flip null once for example like so :

console.log(!null) // that would output --> true 

If you flip it twice like so :

console.log(!!null) // that would output --> false 

Same with undefined or false .

That would work for all cases even when there's a string but it's length is zero. Now if you want it to also work for the number 0 (which would become false if it was double flipped) then your if would become:

Источник

javascript check for not null

Below is a code snippet, where we retrieve a form value. Before further processing check if the value is not null..

var val = document.FileList.hiddenInfo.value; alert("val is " + val); // this prints null which is as expected if (val != null) < alert("value is "+val.length); // this returns 4 >else

10 Answers 10

this will do the trick for you

while technically this works, a double not (!!) is a programming faux-pas. It is really the equivalent of if(val) , which is much clearer to read. I would stick to that (fyi Ujwal, !!val should technically work in C or C++ also) see here for javascript 'truthiness' values: janosch.woschitz.org/javascript-equality-comparison

!! is just a double negative, so it's literally saying if(val.exists). I still like the way it looks though!

It's not a simple double negative. It's a transforming double negative. You are basically transforming the variable to a boolean. There's a lot to say on the subject but suffice it to say that in cases where your variable is 0 , false , null , undefined or some such value that resolves to true with one !, you're going to get false for . It should be used sparingly if at all.

There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.

1. Strict Not Version

The Strict Not Version uses the "Strict Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6. The !== has faster performance, than the != operator because the Strict Equality Comparison Algorithm doesn't typecast values.

2. Non-strict Not Version

The Non-strict version uses the "Abstract Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3. The != has slower performance, than the !== operator because the Abstract Equality Comparison Algorithm typecasts values.

3. Double Not Version

Источник

Оцените статью