JavaScript The logical NOT operator (!)


Example

The logical NOT (!) operator performs logical negation on an expression.

Syntax:

!expression

Returns:

  • a Boolean.

Description

The logical NOT (!) operator performs logical negation on an expression.

Boolean values simply get inverted: !true === false and !false === true.
Non-boolean values get converted to boolean values first, then are negated.

This means that a double logical NOT (!!) can be used to cast any value to a boolean:

!!"FooBar" === true
!!1 === true
!!0 === false

These are all equal to !true:

!'true' === !new Boolean('true');
!'false' === !new Boolean('false');
!'FooBar' === !new Boolean('FooBar');
![] === !new Boolean([]);
!{} === !new Boolean({});

These are all equal to !false:

!0 === !new Boolean(0);
!'' === !new Boolean('');
!NaN === !new Boolean(NaN);
!null === !new Boolean(null);
!undefined === !new Boolean(undefined);

Examples:

!true         // false
!-1           // false
!"-1"         // false
!42           // false
!"42"         // false
!"foo"        // false
!"true"       // false
!"false"      // false
!{}           // false
![]           // false
!function(){} // false

!false        // true
!null         // true
!undefined    // true
!NaN          // true
!0            // true
!""           // true