nested if javascript
if(a == 'value'){
doSomething();
if(b == 'another value'){
doAnotherThing();
}
}
nested if javascript
if(a == 'value'){
doSomething();
if(b == 'another value'){
doAnotherThing();
}
}
js nested if else
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!!!");
}
}
}
better way to do nested if statements javascipt
/_ 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');
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us