Javascript Logical OR operator in return statement of a function

1.1k views Asked by At

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?

1

There are 1 answers

1
Alicia Sykes On BEST ANSWER
(title) => !!title || "Title is required"]

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:

function xxxx (title) {
  return !!title || "Title is required"];
}

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

const checkTitle = (title) => !!title || "Title is required"

// 1. No parameters, should print "Title is required"
console.log('Test 1', checkTitle()); 

// 2. Parameter presentbut empty, should print "Title is required"
console.log('Test 2', checkTitle("")); 

// 3. Title present, and valid, should preint 'true'
console.log('Test 3', checkTitle('Hello World!')); 


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.