Explain Codes LogoExplain Codes Logo

What is the !! (not not) operator in JavaScript?

javascript
prompt-engineering
best-practices
performance
Alex KataevbyAlex Kataev·Aug 30, 2024
TLDR

!! is an express route to turning any value into its boolean form: true if the value is truthy, and false if it is falsy. This cunning trick serves as JavaScript's equivalent of a boolean conversion shortcut.

Example:

let isFilled = !!'Text'; // true, because even code appreciates a good read let isEmpty = !!''; // false, because an empty string is as silent as a muted DJ

Unveiling the power of the double bang!!

Beyond its basic usage, !! can pull off some neat tricks in your JavaScript code:

  1. Feature Detection: !! excels in feature detection without the need of extensive error handling. !!(element.dataset) quickly checks if the dataset property exists.
  2. Code Cleanliness: !! helps in making your code more readable and maintainable, especially for conditional assignments.this.isActive = !!user.isActive; is better than this.isActive = user.isActive ? true : false;
  3. Code Compression: In situations where fewer bytes mean more performance, !! stands tall due to its sheer brevity.
  4. Explicit Booleans: !! comes handy when calling functions that strictly require boolean arguments. It ensures the argument is always true or false and never a truthy or falsy value.

Remember, !! and Boolean() both convert a given value to boolean but the choice between them should consider code readability and maintainability.

The fine print of the double bang operation

The truth about truthy and falsy

JavaScript values may not always simplify to true or false. However, using !!, they will. Let's understand this with the help of some examples:

  • Falsy values: These evaluate to false via !! and include 0, -0, NaN, null, undefined, and the value false. All known villains of truth.
  • Truthy values: These convert to true and include all non-empty strings, all objects, and all numbers except 0 and NaN. They are the heroes.

Mistakes to avoid with !!

  • Mishandling JavaScript can spell disaster. Avoid pitting !! against property checks- hasOwnProperty or in are the right tools for the task.
  • Overusing !! can lead to redundantly converting variables into booleans when the environment already evaluates truthy or falsy values.
  • New developers, or those not in the know, might miss the point of !!, leading to confusion. So, keeping things transparent and understandable through Boolean() can, at times, be preferable.

Optimizing with !!

  • The execution time difference between Boolean() and !! is minuscule but worth consideration in high-performance applications where microseconds could make a difference.