November 8, 2023
Double negation in JavaScript is a logical operation that turns truthy values to true
and falsy values to false
. It is a common technique used to coerce a value to a boolean type.
What is double negation?
In JavaScript, the not operator (!
) is used to invert a boolean value. When it is applied twice (!!
), it effectively converts a value to its boolean equivalent without changing its truthiness. This is known as double negation.
Truthy and falsy values
JavaScript has values that are "truthy" and "falsy". Truthy values are those that evaluate to true
in a boolean context, and falsy values evaluate to false
. The only falsy values in JavaScript are:
false
0
and0
""
(empty string)null
undefined
NaN
Every other value is truthy, including objects, non-empty strings, and arrays.
Using double negation
Here’s how you can use double negation:
const truthyValue = "hello"; const booleanValue = !!truthyValue; // true
const falsyValue = 0; const booleanValue = !!falsyValue; // false
Practical examples
Double negation can be particularly useful in conditional statements and when you need to ensure a value is a true boolean:
const value = "some string"; if (!!value) { // This block will run because 'value' is truthy }
const mightBeFalsy = undefined; const isDefinitelyBoolean = !!mightBeFalsy; // false
Comparison with Boolean constructor
An alternative to double negation is using the Boolean
constructor. However, using !!
is generally preferred for its brevity and speed:
const value = "some value"; const booleanValue = Boolean(value); // true
Edge cases
While double negation is straightforward, it’s important to consider JavaScript’s type coercion, especially with objects and arrays:
const emptyArray = []; const notEmpty = !!emptyArray; // true, because an empty array is an object and hence truthy
Common pitfalls
Be cautious with double negation when dealing with numbers and strings:
const zero = 0; const isEmpty = !!zero; // false, but zero is a valid number that might not represent emptiness
In summary, double negation is a concise way to convert any JavaScript value to a strict boolean. It’s a powerful tool when used with an understanding of truthy and falsy values and can simplify checks in your code. Remember to consider context when working with different data types to avoid unintended consequences.
Ship faster, worry less with Basedash
How to Sort Object Array by Boolean Property in JavaScript
Max Musing
How to Truncate Date in MySQL
Max Musing
What is evented I/O for V8 JavaScript?
Max Musing
Replace + with Space in JavaScript
Max Musing
How to Sort JavaScript Objects by Key
Max Musing
How to Scroll Automatically to the Bottom of a Page in JavaScript
Max Musing