Hello coders,
When I’m flicking through the code, I don’t understand the parallel symbol meaning “||” Could you please inform me why we use it and how it works?
Big thanks in advance!
const formInputsContainValues = titleInput.value **||** dateInput.value **||** descriptionInput.value;
Hi,
This ||
is the Logical OR operator. It is used to return the first thing that is true. In your code for example, titleInput.value || dateInput.value || descriptionInput.value;
, it first checks for the value of titleInput
. If it has a value, that value will be assigned to formInputsContainValues
. If not, it will look for the value of dateInput
and so on.
true || false
returns true
false || true
returns true
false || false
returns false
In simple terms, think of the Logical OR operator as: Is this true? If not, is this true? If not, is this true?
I hope this helps!
1 Like
It is exactly inspiring. Thanks for your precious time. More power to your elbow!
I’m just trying to understand the detail in this information. As far as I can understand from the search results:
It’s been available across browsers since July 2015.
It is typically used with boolean (logical) values.
Can’t we use a classical if statement or else statement with this code? Are they the same, or in which situations do we diverge them?
Happy coding!
You’re welcome!
About the statements from search results, I think the first one is a bit misleading. The OR operator has been part of JavaScript since the beginning. It even worked in browsers before 2015. The statement makes it look like it’s a new feature, but it’s not.
Yes, it is typically used with boolean values. And yes, we can use if
statements instead of the OR operator. But it’s less clean and less efficient. Let’s use if statements in the code you shared as an example.
let formInputsContainValues;
if (titleInput.value) {
formInputsContainValues = titleInput.value;
} else if (dateInput.value) {
formInputsContainValues = dateInput.value;
} else if (descriptionInput.value) {
formInputsContainValues = descriptionInput.value;
} else {
formInputsContainValues = null;
}
As you can see, it works with if statements as well, but what we had as one simple line of code is about 10 lines now.
Let me know if you have any questions.
Happy coding!
1 Like