(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.