I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered.
var startGame = function() {
var quizAnswers = {
name: prompt("What is your name?").toUpperCase(),
age: prompt("What is your age?"),
snack: prompt("What is your favorite type of snack out of the following: ice cream, apple, chips, cookies?").toUpperCase()
};
quizAnswers.confirmAge = function () {
while (isNaN(this.age) === true) {
this.age = prompt("The age that you entered- " + this.age + " -is not a number. Please enter a number.");
};
};
quizAnswers.confirmAge();
quizAnswers.confirmSnack = function () {
while ((this.snack !== "ICE CREAM") && (this.snack !== "APPLE") && (this.snack !== "CHIPS") && (this.snack !== "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is unrecognized. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
};
quizAnswers.confirmSnack();
The program collects the user's name, age, and favorite snack, then verifies if the age is a number and if the snack matches any of the options provided. I managed to make the confirmSnack function work after some trial and error with the while loop, as shown above. However, I'm puzzled why the code uses && instead of ||, and if there's a way to simplify it like:
while (this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is invalid. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
So, my questions are regarding the rationale behind using && over ||, and whether there's a more concise way to write this code without repeating "this.snack !==" four times. I'm still learning, so please try to explain in simple terms.