26
loading...
This website collects cookies to deliver better user experience
let x;
x = "JavaScript"; // truthy
x = ""; // falsy
x = {}; // truthy
x = 0; // falsy
!
), we can convert a truthy value to false
and a falsy value to true
:let x;
x = !"JavaScript"; // false
x = !""; // true
x = !{}; // false
x = !0; // true
!
always returns a boolean value: It first converts the truthy or falsy value to its corresponding boolean value (truthy corresponds to true
and falsy to false
), then returns the negated boolean. For example, !{}
first converts {}
to true
and then returns the opposite of true
, which is false
.!!
) allows us to succinctly convert a non-boolean value to its corresponding boolean value:let x;
x = !!"JavaScript"; // true
x = !!""; // false
!!"JavaScript"
, for instance:"JavaScript"
is truthy, so it is converted to true
!
converts true
to false
!
converts false
to true
!!
is not an operator––it's just two logical NOT operators chained together. In fact, we can use as many !
s as we like (and make our JavaScript look like it's gone into expletive mode):const x = !!!!!"s***"; // false
!!
, but I think there are a few instances where it can be useful. Consider a function that performs logic on non-boolean values that we want to ensure returns a boolean value:function isValidUser(user: { name: string; bio: string }) {
return !!(user.name && user.bio); // ...
}
!!
as a shortcut for checking if a list has any elements; this is something I often see in React:function FruitDisplay({ fruit }) {
const hasFruit = !!fruit.length;
return (
hasFruit && (
<>
<h3>Available fruit:</h3>
<ul>
{fruit.map((f) => (
<li>{f}</li>
))}
</ul>
</>
)
);
}
function App() {
const fruit = ["apple", "orange", "grape"];
// ...
return (
<FruitDisplay fruit={fruit} />
//...
);
}
!!
decreases readability and is used in situations that could be refactored to be more explicit. In our previous list length example, I'd argue that checking for > 0
or !== 0
is more clear:function FruitDisplay({ fruit }) {
const hasFruit = fruit.length > 0; // or fruit.length !== 0
// ...
}
Boolean
function does the same thing as !!
and is arguably more readable and easier to understand:let x;
x = !!"" === Boolean(""); // true
x = !!"JavaScript" === Boolean("JavaScript"); // true
true
and falsy values become false
. It's a concise way to coerce any value to a boolean but can also sacrifice readability.!!
? What situations do you find it useful or harmful? Let me know your thoughts below!