wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes Testing for true or false Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Testing for true or false" Watch "Testing for true or false" New topic
Author

Testing for true or false

James Davidson
Greenhorn

Joined: Oct 14, 2004
Posts: 9
What is the proper way to test for a true or false condition in JavaScript? In Java, one would simply code: if (condition) but in JavaScript, it is my understanding that this code tests for existence of a variable, function, etc. Therefore, it would seem to me that the proper way to test for a true or false condition in JavaScript would be to explicitly code: if (condition == true). Is my understanding correct?
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
You can do either one. Basically when you do it as if(object) it checks to see if anything exsits if the object exsists. I usually only do it when I am certain that the data stored in the variable/object is a boolean.

I usually use == true if I am writing a script for beginners since it is easier for them to understand.

Eric
James Davidson
Greenhorn

Joined: Oct 14, 2004
Posts: 9
Eric,

Thanks for your prompt reply.

Re: "I usually only do it when I am certain that the data stored in the variable/object is a boolean."

Does that mean that, in this case, JavaScript will evaluate the value contained in the object? It seems to me that, in this case, JavaScript would evaluate if (booleanObject) as true regardless of whether the value contained in "booleanObject" is true or false.
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
it usually checks to see if the object exsists.

For example:

if(document.all) checks to see id the document all object exsists. It would return true for IE and false for Mozilla.

Running the following script can show you what problems can occur:


You might get the wrong results depending on what type of information you are looking at.

Eric
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Testing for true or false
 
Similar Threads
JSTL tag c:if
if condition problem ( ex from k&b )
&& and &
ajax synchronicity?
beginning methods help