JavaScript If statement condition with no operator? What does it do? JavaScript If statement condition with no operator? What does it do? javascript javascript

JavaScript If statement condition with no operator? What does it do?


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 ({}) {    alert('{}');  }  if(window) {    alert('window!');  }  if(true) {    alert('true!');  }  if('hell yeah') {    alert('hell yeah!');  }</script>


It's because the JavaScript engine coerces any type into a boolean when testing a condition. It as if you were doing

// Coerce it to a boolean using !!if (!!window.XMLHttpRequest) {   xmlhttp = new XMLHttpRequest();}


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.