views:

56

answers:

4

I am used to if statements having a condition where ( x < y ) or ( x == y ). But in cases where there is no operator, what does the if statement check exactly? i.e. in the example below if (window.XMLHttpRequest)... what's the condition?

Thanks.

if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
A: 

As i understand, it will try to convert variable (inside if statement) to boolean, and than as usual check for true or false. In this particular case, it will check, if XMLHttpRequest element of window is exist. If there is no XMLHttpRequest - it will be NULL, and then NULL will be converted to false. P.S. I recommend you to find some good javascript reference.

Zakus
+1  A: 

As long as the expression inside the parentheses returns something other than false, null, 0 or undefined... the block in the if statement will be executed :-)

In fact all of the following will work:

<script>
  if (3) {
    alert('3');
  }
  if(window) {
    alert('window!');
  }
  if(true) {
    alert('true!');
  }
  if('hell yeah') {
    alert('hell yeah!');
  }

</script>
DKinzer
A: 

This checks whether there exists a property on window called XMLHttpRequest whose "truthiness" is true. Javascript interprets a variety of values as true: true, any non-0 numeric value, any non-null object reference, or (I think) any non-empty string.

In this case, the code is testing whether the browser supports the XMLHttpRequest property, which is the constructor function for an object that sends asynchronous requests to the server in the above-mentioned browsers. If the browser defines this function, the if statement will evaluate to true.

RMorrisey
A: 

in some languages the predicate really has to return a boolean. In javascript this isn't the case.

Some case like 0 or false (there might be others) are false, the rest is true

davyM