Using && in Javascript

By: Syed Fazal Viewed: 153234 times    

The logical AND operator in JavaScript is indicated by the double ampersand ( && ):

Logical AND can be used with any type of operands, not just Boolean values. When either operand is not a primitive Boolean, logical AND does not always return a Boolean value:

  • If one operand is an object and one is a Boolean, the object is returned.
  • If both operands are objects, the second operand is returned.
  • If either operand is null , null is returned.
  • If either operand is NaN , NaN is returned.
  • If either operand is undefined , an error occurs.

var bTrue = true;

var bFalse = false;

var bResult = bTrue && bFalse;

Logical AND behaves as described in the following truth table:

Operand 1 Operand 2 Result

true             true             true

true             false            false

false            true             false

false            false            false

Just as in Java, logical AND is a short-circuited operation, meaning that if the first operand determines the result, the second operand is never evaluated. In the case of logical AND, if the first operand is false, no matter what the value of the second operand, the result can’t be equal to true. Consider the following example:

var bTrue = true;

var bResult = (bTrue && bUnknown); //error occurs here

alert(bResult); //this line never executes

This code causes an error when the logical AND is evaluated because the variable bUnknown is undefined. The value of variable bTrue is true , so the logical AND operator continued on to evaluate variable bUnknown . When it did, an error occurred because bUnknown is undefined and, therefore, cannot be used in a logical AND operation. If this example is changed so that a is set to false , the error won’t occur:

var bFalse = false;

var bResult = (bFalse && bUnknown);

alert(bResult); //outputs “false”

In this code, the script writes out the string “false” , the value returned by the logical AND operator. Even though the variable bUnknown is undefined, it never gets evaluated because the first operand is false . You must always keep in mind short-circuiting when using logical AND.

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial