The logical NOT operator

The NOT operator is a unary operator. It accepts only a single operand and converts that operand into its Boolean representation, then inverts it, so that truthy items become false and falsy items become true:

!1;    // => false
!true; // => false
!'hi; // => false

!0; // => true
!''; // => true
!true; // => false

Internally, the NOT operator will perform the following:

  1. Cast the operand to a Boolean (Boolean(operand))
  2. If the resulting value is true, then return false; otherwise, return true

As discussed in the Conversion to a Boolean section in the last chapter, a typical idiom for converting a value to its Boolean representation is the double NOT (that is, !!value) as this effectively reverses the truthiness or falsiness of the value twice and evaluates to a Boolean. The more explicit and slightly more preferred idiom is to use Boolean(value), as the intention is far clearer than with !!.

As a result of there being only seven falsy values in JavaScript, the NOT operator can only evaluate to true in these seven scenarios:

!false;     // => true
!''; // => true
!null; // => true
!undefined; // => true
!NaN; // => true
!0n; // => true
!0; // => true

JavaScript's rigid definition of falsiness and truthiness is reassuring. It means that even if someone constructs an object with all manner of primitive representations (imagine an object with valueOf() that returns a falsy value), all internal Boolean coercions will still only ever return false for the seven falsy values and nothing else. That means we only need to worry about those seven (it could be much worse...).

On the whole, usage of the logical NOT operator is very straightforward. It's a well-understood syntax across programming languages with clear semantics. As such, there is not a lot in the way of best practices concerning it. At the very least, it's best to avoid too many double negatives in your code. A double negative is when an already negatively-named variable is applied to the NOT operator, like so:

if (!isNotEnabled) {
// ...
}

This is cognitively expensive for those who read your code and is therefore liable to misunderstanding. It's best to use positively-named Boolean variable names so that any logical operations using them are straightforward to comprehend. In this situation, we would simply rename our variable and reverse the operation, like so:

if (isEnabled) {
// ...
}

The logical NOT operator, in summary, is most useful in Boolean contexts such as if() and while(), though is also idiomatically found in the double-NOT !! operation. And it is technically the only operator in JavaScript that is guaranteed to return a Boolean value regardless of its operand's type. Next, we'll explore the AND operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.118.99