How to use Boolean Operator AND operator

Description

The boolean operator AND operator is represented by the double ampersand << and is applied to two values:

var result = true && false;

Boolean operator AND behaves as described in the following truth table:

OPERAND 1OPERAND 2RESULT
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

Boolean operator AND can be used with any type of operand, not just Boolean values.

When either operand is not a primitive Boolean, AND does not always return a Boolean value; instead, it does one of the following:

  • If the first operand is an object, the second operand is returned.
  • If the second operand is an object, the object is returned only if the first operand evaluates to true.
  • If both operands are objects, then the second operand is returned.
  • If either operand is null, then null is returned.
  • If either operand is NaN, then NaN is returned.
  • If either operand is undefined, then undefined is returned.

AND is a short-circuited operator: if the first operand determines the result, the second operand is not evaluated.

Example


var found = true;
var result = (found && someUndeclaredVariable);    //error occurs here
console.log(result);    //this line never executes

found = false;
var result = (found && someUndeclaredVariable);    //no error
console.log(result);    //works





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions