Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing for true or false

 
James Davidson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic