- Conditional (ternary) operator. In the function body, make sure to put return before the condition.
fruits = ['aa','bb','cc','dd'];
const fruit = fruits.map(fruit =>{
return fruit === 'aa'? 'aaaaaa' : fruit;
});
console.log(fruit); //output: [ 'aaaaaa', 'bb', 'cc', 'dd' ];
- A switch example
let shopItem = 'apple';
switch(shopItem){
case 'apple':
console.log('Apples are 10/lb.');
break;
case 'orange':
console.log('Oranges are 11/lb.');
break;
case 'peach':
console.log('Peaches are 12/lb.');
break;
default:
console.log('Invalid Item');
break;
}
const getUserChoice = userInput =>{
if (userInput ==='rock' || userInput==='paper' || userInput ==='scissors'){
return userInput;
} else {
console.log('error');
}
}
const getComputerChoice = () => {
const computerDice = Math.floor(Math.random()*3);
switch (computerDice){
case 0:
return 'rock';
break;
case 1:
return 'paper';
break;
default:
return'scissors';
break;
}
}
const determineWinner =(userChoice,computerChoice)=>{
if (userChoice === computerChoice){
return 'tie'
} else if(userChoice === 'rock' && computerChoice==='paper'){
return 'computer won';
} else if (userChoice === 'paper' && computerChoice ==='scissors'){
return 'computer won';
} else if (userChoice ==='scissors' && computerChoice === 'rock'){
return 'computer won';
} else {
return 'user won';
}
}
const playGame = (userChoice,computerChoice)=>{
userChoice = getUserChoice('paper');
computerChoice = getComputerChoice();
console.log(`You threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(`The resule is: ${determineWinner(userChoice, computerChoice)} `);
}
playGame();
The output for this code:
Top comments (0)