I have a variable that checks the length of some values; if one fails, var pass is set to false. Another function checks the validity of an email address and sets it to false if it doesn’t pass the test. I’m trying to make a custom error message.
Is it better to use a ternary operator like this, or a nested if-statement. Or is there a much simpler way to do it?
var mail = true;
var pass = true;
var err = '';
(mail && pass) ? err = 'mail and pass both true' : (!mail && pass) ? err = 'not mail and is pass' : (mail && !pass) ? err = 'is mail and not pass' : err = 'neither pass nor mail';
The only syntactic issue you might run into is the associativity of the ternary operator. Using brackets to reduce ambiguity helps.
The main problem is that that line is barely readable by humans. Nested ifs are much easier to read, and maintain. Imagine yourself in two months coming back to that line and trying to decipher it.