Skip to content
Advertisement

Javascript Logical OR operator in return statement of a function

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:

JavaScript

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?

Advertisement

Answer

JavaScript

This line is saying:
If title is present, return true, otherwise return "Title is required".

Let’s break it down…


To start with, the arrow function is just shorthand for:

JavaScript

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 return true, wheras false || 'some text' will return some text


Here are some example, try running the snippet to see the outputs

JavaScript

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 or true would be accepted as valid.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement