Posted on: November 12, 2022|Amrish Kushwaha

How does the Logical NOT operator behave in Javascript?

How does the Logical NOT operator behave in Javascript?

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:

Execution Steps

The execution of logical NOT expression happens in these steps.

  1. First, the operand or expression is evaluated
  2. Then evaluated value is coerced to the corresponding Boolean primitive.
  3. 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

  1. If the value of type Boolean, return it.
  2. 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
  3. 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.

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Related category articles: