• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Testing for true or false

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic