I came across this code: this.vertical = vertical !== undefined ? !!vertical : this.vertical;
and I’m curious about the purpose of using !!
here and how it works.
I’ve been working with JavaScript for a while, and the !!
operator is one of those handy little tricks I use often. Essentially, !!
converts any value to a boolean.
The first !
flips the truthiness (true becomes false, false becomes true), and the second !
flips it back—resulting in a strict true
or false
. So in your code, !!vertical
ensures that vertical is a boolean, not just a truthy or falsy value. It’s super useful when you want a clean boolean flag.
"Building on that, I’ve used !!
quite a bit to coerce values to booleans. Imagine you have a variable that might be a string, a number, null, or undefined. Using !!variable
guarantees you get either true
or false
.
In your example, it’s checking if vertical is defined, then forcing it to be a boolean. This avoids weird cases where, say, "0"
or null
might behave unexpectedly in conditions. It’s a simple and idiomatic way to clean up data and make sure you’re working with explicit booleans."
To add to that, think of !!
as a quick ‘cast’ to boolean in JavaScript, especially handy in conditional logic or settings where only true
or false
make sense. Your line this.vertical = vertical !== undefined ? !!vertical : this.vertical;
means if vertical is defined, convert it to true
or false
explicitly—so any truthy value like a non-empty string or a non-zero number becomes true
, and falsy values like 0
, null
, or ''
become false
. This exact match keyword in all three answers — !!
operator — is a very common pattern to make booleans explicit and avoid subtle bugs.