better way to do nested if statements javascipt
var word = ['rock', 'paper', 'scissors'];
var player1 = word[Math.floor(Math.random() * word.length)];
var player2 = word[Math.floor(Math.random() * word.length)];
var player1Image = document.querySelectorAll("img")[0].setAttribute("src", "images/" + player1 + ".png");
var player2Image = document.querySelectorAll("img")[1].setAttribute("src", "images/" + player2 + ".png");
if(player1 === "rock"){ // rock
if(player2 === "scissors"){
player1Image;
player2Image;
console.log(player1 + " beats " + player2 + ", player1 wins");
} else if(player2 === "paper"){
player1Image;
player2Image;
console.log(player2 + " beats " + player1 + ", player2 wins");
} else {
player1Image;
player2Image;
console.log("Draw!!!")
}
} else if(player1 === "scissors"){ // scissors
if(player2 === "rock"){
player1Image;
player2Image;
console.log(player2 + " beats " + player1 + ", player2 wins");
} else if(player2 === "paper"){
player1Image;
player2Image;
console.log(player1 + " beats " + player2 + ", player1 wins");
} else {
player1Image;
player2Image;
console.log("Draw!!!");
}
} else { // paper
if(player1 === "paper"){
if(player2 === "rock"){
player1Image;
player2Image;
console.log(player1 + " beats " + player2 + ", player1 wins");
} else if(player2 === "scissors"){
player1Image;
player2Image;
console.log(player2 + " beats " + player1 + ", player2 wins");
} else {
player1Image;
player2Image;
console.log("Draw!!!");
}
}
}
4.5
8
/_ return early when invalid conditions found _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red
console.log('red');
// condition 3: must be big quantity
if (quantity > 10) {
console.log('big quantity');
}
}
Thank you!
8
0
Are there any code examples left?
New code examples in category TypeScript
-
TypeScript 2022-03-27 19:30:45 typescript promise
-
TypeScript 2022-03-27 17:25:44 how to search for imports in vscode
-
TypeScript 2022-03-27 17:15:20 angular formgroup mark as touched
-
TypeScript 2022-03-27 17:05:06 use of slice and splice add elements array
-
TypeScript 2022-03-27 16:50:23 android studio loop through all objects in layout
-
TypeScript 2022-03-27 14:35:08 wergensherts meaning
-
TypeScript 2022-03-27 13:50:15 remove all the elements from a numpy array python
-
TypeScript 2022-03-27 12:35:49 redux toolkit typescript install
-
TypeScript 2022-03-27 12:35:30 laravel middleware for apis