How to use Boolean Operator NOT in Javascript

Description

The logical NOT operator is represented by an exclamation point ! and may be applied to any value in Javascript.

This operator always returns a Boolean value, regardless of the data type it's used on.

The logical NOT operator first converts the operand to a Boolean value and then negates it. The logical NOT behaves in the following ways:

  • If the operand is an object, false is returned.
  • If the operand is an empty string, true is returned.
  • If the operand is a nonempty string, false is returned.
  • If the operand is the number 0, true is returned.
  • If the operand is any number other than 0 (including Infinity), false is returned.
  • If the operand is null, true is returned.
  • If the operand is NaN, true is returned.
  • If the operand is undefined, true is returned.

Example


console.log(!false);      //true
console.log(!"asdf");     //false
console.log(!0);          //true
console.log(!NaN);        //true
console.log(!"");         //true
console.log(!12);         //false
/*from  w  ww . j av  a 2 s  .co  m*/

The code above generates the following result.

Example 2

The logical NOT operator can be used to convert a value into its Boolean equivalent.

By using two NOT operators, you can simulate the Boolean() casting function.


console.log(!!"asdf");     //true
console.log(!!0);          //false
console.log(!!NaN);        //false
console.log(!!"");         //false
console.log(!!12);         //true
// w  w w .  ja v a  2 s .  co  m

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




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