The logical NOT operator is ! and can be applied to any value in ECMAScript.
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.
Input | Not Input |
---|---|
an object | false is returned. |
an empty string | true is returned. |
a nonempty string | false is returned. |
number 0 | true is returned. |
any number other than 0 (including Infinity) | false is returned. |
null | true is returned. |
NaN | true is returned. |
undefined | true is returned. |
The following example illustrates this behavior:
console.log(!false); //true console.log(!"blue"); //false console.log(!0); //true console.log(!NaN); //true console.log(!""); //true console.log(!12345); //false
The logical NOT operator can convert a value into its Boolean equivalent.
By using two NOT operators in a row, you can effectively simulate the behavior of the Boolean() casting function.
console.log(!!"blue"); //true console.log(!!0); //false console.log(!!NaN); //false console.log(!!""); //false console.log(!!12345); //true