Logical NOT operator
Logical NOT is one of the unary operators in Javascript. A unary operator is an operator where no of operands is 1.
Syntax:
This is the syntax for the logical NOT operator
!operand
or
!expression
Execution steps for Logical NOT:
The execution of logical NOT expression happens in these steps.
- First, the operand or expression is evaluated
- Then evaluated value is coerced to the corresponding Boolean primitive.
- Now the result from step 2 will be logically negated.
Example:
!(2 + "1")
// 1. !("21")
// 2. !(true)
// 3. false
// so the result is `false`
Note: Conversion of any value to Boolean primitive:
Rules for coercion of any value to boolean primitive are straightforward
- If the value of type Boolean, return it.
- If the value is any of these values ( undefined, null, -0, +0, 0, “”, ‘’, ``, NaN ) or value is any object having the [[IsHTMLDDA]] internal slot such as the
document.all
, then return false - In any other case, return true.
Examples of Logical NOT:
console.log(![]) // false
console.log(![""]) // false
console.log(![null]) // false
console.log(![undefined]) // false
console.log(![0]) // false
console.log(![NaN]) // false
console.log(!["abc"]) // false
console.log(![[]]) // false
console.log(![{}]) // false
console.log(!{}) // false
console.log(!{ a: "b" }) // false
console.log(!true) // false
console.log(!false) // true
console.log(!0) // true
console.log(!1) // false
console.log(!1.23) // false
console.log(!-1.23) // false
console.log(!-0.23) // false
console.log(!NaN) // true
console.log(!null) // true
console.log(!undefined) // true
console.log(!"") // true
console.log(!"abc") // false
console.log(!"123") // false
console.log(!"0") // false
console.log(!function abc() {}) // false
console.log(!new Function()) // false
Usage of logical NOT
- Calculate the corresponding boolean primitive of any value
Logical NOT can be used to calculate the corresponding boolean primitives of a non-boolean value
For e.g.:
const value = "abc" const equivalentBooleanValue = !!value console.log(equivalentBooleanValue) // true
- If the value is of type Boolean then
!!value === value // in the case when the value is boolean.