6

How does the Logical NOT operator behave in Javascript?

 1 year ago
source link: https://www.frontendroom.com/blog/how-does-the-logical-not-operator-behave-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Table of contents



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 Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK