snippetjavascriptTip
What does the double negation operator do in JavaScript?
Viewed 0 times
doublejavascriptwhatdoesthenegationoperator
Problem
JavaScript's negation operator (
Using the double negation operator is functionally equivalent to using the
!) is a unary operator, used to invert the truth value of its operand. When used twice, known as the double negation operator (!!), it can be used to convert a value to a boolean.Using the double negation operator is functionally equivalent to using the
Boolean() function, which we explored in depth in a previous article. In terms of readability and usability, I would still suggest using the Boolean() function. It conveys the intent of the operation more clearly, and it's easier to understand at a glance.Solution
Implementation for What does the double negation operator do in JavaScript?:
See the code snippet for the complete implementation.
const x = 1;
const y = null;
!!x; // true
!!y; // falseSee the code snippet for the complete implementation.
Code Snippets
const x = 1;
const y = null;
!!x; // true
!!y; // falseconst x = 1;
const y = null;
Boolean(x); // true
Boolean(y); // false
const values = [0, 0, 2, 0, 3];
// Kinda readable, but not great
values.filter(x => !!x); // [2, 3]
// Arguably more readable
values.filter(Boolean); // [2, 3]Context
From 30-seconds-of-code: double-negation-operator
Revisions (0)
No revisions yet.