Testing for true or false

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?

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

posted Oct 21, 2004 07:19:00

0

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: 15385

6

posted Oct 21, 2004 08:26:00

0

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.