Javascript Reference
Categories: Operators

javascript Operators &&

@March 15, 2008, 1:22 a.m.
&& Firefox/Netscape/NN 2 IE 3 ECMA 1  

  

The AND operator compares two Boolean expressions for equality. If both expressions evaluate to true, the result of the && operator also evaluates to true; if either or both expressions are false, the && operator evaluates to false.

 

A Boolean expression may consist of a comparison expression (using any of the many comparison operators) or a variety of other values. Here are the most common data types, values, and their Boolean value equivalent.

Data type Boolean equivalent
Number other than zero true
Zero false
Any nonempty string true
Empty string false
Any object true
null false
undefined false
 

Using this information, you can create compound conditions with the help of the && operator. For example, if you want to see if someone entered a value into a form field and it is a number greater than 100, the condition would look like the following:

var userEntry = document.forms[0].entry.value ;
if (userEntry&& parseInt(userEntry) >= 100) {
    ...
} 
 

If the user had not entered any value, the string would be an empty string. In the compound condition, when the first operand evaluates to false, the && operator rules mean that the entire expression returns false (because both operands must be true for the operator to return true). Because evaluation of expressions such as the compound condition are evaluated from left to right, the false value of the first operand short-circuits the condition to return false, meaning that the second operand isn't evaluated.

 
Example
 
if (a <= b && b >= c) {
    ...
}

Powered by Linode.