I am using Vuetify, specifically the v-text-field from inside v-form. Each of these v-text-fields has a property called rules, used for validation. That property accepts an array with a bunch of functions. This is where I've stumbled over a weird-ish piece of code:
(title) => !!title || "Title is required"
So, the idea is that this function gets the value from the input, and if the length is equal to 0, then the error message "Title is required" is shown. My question is: what does this function actually return?
Let's break it down...
To start with, the arrow function is just shorthand for:
Next, the
!!
is a double negation, effectively just the logical not opperator twice. The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result.E.g.
!!'hello'
-->true
,!!0
-->false
,!!undefined
-->false
The next part is a comparison. The
||
is OR opperator, so if the first half is true / present, then it will be returned, if not, the part after the||
will be returned.E.g.
true || 'some text'
will returntrue
, wherasfalse || 'some text'
will returnsome text
Here are some example, try running the snippet to see the outputs
It's not the best code, because it's not super clear, and you usually don't want to mix types like this. It also doesn't check if the title is a valid type, so
123
ortrue
would be accepted as valid.