I’m using React JS.
My current code works, but I’m looking to make it more concise.
I’m doing validation for user inputs. I’m saying "if the user input doesnt match A or B or O, then set it as invalid answer and turn it red".
switch (_selectedField) {
case 'Blood Type':
if (userInput !== 'A' | userInput !== 'B'|userInput !== 'O')
setIsInValid(true)
I have multiple Fields where user inputs answers. That’s what the switch statement is for, to set condition for each _selectedField.
I’m wanting to rewrite my OR (||) operator, as it could become excessive for Fields that have 30 correct answers.
Please let me know a more effective way than using (||) and if possible, please give me some examples.
Thank you so much
2
Answers
I would use includes, like this:
The guy above me already provided you with a better answer, but the thing is, your logic is incorrect for the problem you want to solve.
This line is checking if the user input is different from "A", or different from "B" or different from "O".
Of course this condition will always be
false
, since if the input is "A", then it’s not "B" or "O" and so on. You should either use anAND
operator or an identity operator instead of non-identity.Another thing to note is that
|
is not the sign for a logical OR, but instead, of the bitwise OR, which is a totally different thing.You said your code worked and you wanted to optimize it, but it’s clearly full of flaws and you should at least understand the basic logic behind it before even trying to optimize it with built-in functions.