I'm trying to improve my code and have better logging.
Is there an ideal way of how to tell which conditions are false in a list of conditionals?
i.e)
if(isAnimal && isCarnivore && isPlant){
// does something
} else {
// want to console.log all the false conditions in one console.log
}
We could write
let falseString = ""
if (!isAnimal) {
falseString = falseString "is not an Animal";
}
if (!isCarnivore) {
falseString = falseString "is not a Carnivore";
}
if (!isPlant) {
falseString = falseString "is not a Plant";
}
console.log("string of false conditions" , falseString)
Then this would log a string of which conditions are false, but this seems to be a naive solution.
What is a better way to do this in JavaScript?
Thank you!
CodePudding user response:
If the variables are declared globally, you can store their names in an array and check whether it is true
or not by referencing the window
object:
let falseString = ""
isAnimal = true
isCarnivore = false
isPlant = false
const booleans = ['isAnimal', 'isCarnivore', 'isPlant'];
const falseBooleans = booleans.filter(e => !window[e])
console.log(falseBooleans)
CodePudding user response:
You can automate things by creating object of answers and then iterate it
// Create object for answers
const answers = {};
// Alter object with answers...
answers.isAnimal = false;
answers.isCarnivore = false;
answers.isPlant = false;
answers.isHuman = true;
answers.isMineral = false;
answers.isInsect = false;
// Define result strings
let falseAnswers = "False answers is:";
let trueAnswers = "True answers is:";
// Loop answers
for(const answer in answers) {
answers[answer] ? trueAnswers = ` ${answer}` : falseAnswers = ` ${answer}`;
}
// Log
console.log(trueAnswers);
console.log(falseAnswers);