Else if Statement ( the last condition is always picked - javascript

if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else (q1 == "60+")
score = 10;
this is a segment of my code from a multi-choice test but no matter what option I pick, the score variable always chooses 10
A possible error in the format of my code?

The problem is this:
} else (q1 == "60+");
score = 10;
Thanks to ASI, (q1 == "60+") is the expression that is run in the else part, score = 10 is always executed after the if/else. Might do:
} else {
score = 10;
}
Or
} else if (q1 == "60+"){
score = 10;
}
And please always use semicolons to seperate statements and curly braces to annotate blocks.

else shouldn't be followed by a condition. Javascript doesn't require curly braces so it's probably executing the condition as a statement (since else doesn't accept a condition) and then the final score is a separate statement outside of the if-else logic.
If I add braces to your current code, you can see where the problem lies:
if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else
{
(q1 == "60+");
}
score = 10;
So you can see that, because you're using else rather than else if, the "condition" is executed by the else, evaluated to true/false and then thrown away. And then, after the if statement is done, score is set to 10.

Here is problem
else (q1 == "60+")
score = 10;
You are missing if
Or remove this condition.
Else cannot have condition

Related

while loop giving strange results

This while loop works sometimes and sometimes it doesn't. can anyone see why?
I feel like it should start looping, and keep looping till the dealers total is greater than 17 and hit the else block. once it goes into the else block it should update the outcome value. however, sometimes it jumps into the else block and then jumps straight to the console.log(outcome) and tells me it is undefined. sometimes it will return the correct outcome. e.g. it outputs 'dealer wins!'
I feel like I have met every condition?
I have even put in console.logs and the line dealersTotal = total gets updated correctly. why is it not continuously looping?
dealerTwisted = () => {
let dealersTotal = this.state.dealersOverallTotal;
let playersTotal = this.state.playersOverallTotal;
let looping = true;
let outcome = '';
while(looping){
if(dealersTotal < 17){
this.deal2Dealer();
let dealersDeck = this.state.dealersDeck;
let newDealersDeckTotal = [];
for (var i=0; i < dealersDeck.length; i++){
newDealersDeckTotal.push(dealersDeck[i].rankValue)
}
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
dealersTotal = total;
}
else {
if(dealersTotal > 21){
outcome = 'player wins!';
break;
}
else if(playersTotal > dealersTotal){
outcome = 'player wins!';
break;
}
else if (playersTotal == dealersTotal){
outcome = 'tie!';
break;
}
else if (dealersTotal > playersTotal){
outcome = 'dealer wins!';
break;
}
else {
console.log('got here');
break;
}
}
console.log(outcome);
this.setState({resultOutcome: outcome})
break;
}
};
EDIT: Think I have figured it out. It must go into the first if and then it hits the break at the end of the big else. HOWEVER, problem is still that I need it to loop around and only break once all conditions have been covered. solution?
Do you set looping to false anywhere? I can't see it. If not, try setting looping to false at the end of the big else block.
Example:
else {
if(dealersTotal > 21){
outcome = 'player wins!';
}
else if(playersTotal > dealersTotal){
outcome = 'player wins!';
}
else if (playersTotal == dealersTotal){
outcome = 'tie!';
}
else if (dealersTotal > playersTotal){
outcome = 'dealer wins!';
}
else {
console.log('got here');
}
console.log(outcome);
this.setState({resultOutcome: outcome});
looping = false;
}

Can't get my function to run more than once and break my code

I'm trying to run this function until the player or the computer wins 5 times. Without the while loop, it runs one time and everything works fine. As soon as I add a while loop, the function still runs only once and it gives me an undefined return.
function playToFive() {
console.log('Let\'s play Rock Paper Scissors');
var playerWins = 0;
var computerWins = 0;
while (playerWins === 5 || computerWins === 5) {
if (humanVsMachine === 'player') {
playerWins += 1;
} else if (humanVsMachine === 'computer') {
computerWins += 1;
}
return [playerWins, computerWins];
}
}
console.log(playToFive());
while(playerWins === 5 || computerWins === 5)
Your while loop will actually never execute, since you're checking for equality and both playerWins and computerWins are 0 initially.
You may be looking for a condition more like this:
while(playerWins < 5 && computerWins < 5)
Note that we're using the logical AND && instead of the logical OR ||. This is because you don't want to keep looping until both of them win. The logical OR means that even if the computer has won but the player hasn't, we'll continue looping. Only one of the conditions needs to be true for the whole statement to be true.
When we use the logical AND, if one of them is false (meaning, if only one player has reached 5 wins already), then we will break out of the loop as we should.
The next problem is that you have a return statement in your while loop, so after the first execution, even if 5 wins haven't been reached yet, it will return the array of the player's wins and the computer's wins.
You should put the return statement after the loop so that you run the loop 5 times and then return after somebody has won.
And finally, since you haven't provided the rest of the code, I'm not sure if humanVsMachine is actually defined; if you defined that outside of the function then you're good to go.
After the if-else structure is evaluated and executed, a return statement is called unconditionally, thus terminating the loop prematurely. You should place the return after the loop instead. Additionally, the loop condition should be as long as neither player reaches 5 wines (evaluated with the < operator):
while (playerWins < 5 && computerWins < 5 ) {
if (humanVsMachine === 'player') {
playerWins +=1;
} else if (humanVsMachine === 'computer') {
computerWins += 1;
}
}
return [playerWins, computerWins];
You'll need to move the return statement outside the while loop, but you'll also need to change your conditions on your while loop - right now it only runs if either playerWins or computerWins are exactly 5, when in fact it needs to stop running at that point (so while(playerWins < 5 && computerWins < 5))
Return will terminate your loop
function returnMe() {
for (var i=0; i<2; i++) {
if (i === 1) return i;
}
}
alert(returnMe()); Try this out
function playToFive() {
console.log('Let\'s play Rock Paper Scissors');
var playerWins = 0;
var computerWins = 0;
while (playerWins === 5 || computerWins === 5) {
if (humanVsMachine === 'player') {
playerWins += 1;
} else if (humanVsMachine === 'computer') {
computerWins += 1;
}
// return [playerWins, computerWins]; moving code to below
}
return [playerWins, computerWins]; // moved return outside the loop here
}
console.log(playToFive());
You're returning inside the while loop, which will end the looping process. Therefore move your return code outside the loop like below. Also notice that your logical statement is not going to allow the loop to run properly.
function playToFive() {
console.log('Let\'s play Rock Paper Scissors');
var playerWins = 0;
var computerWins = 0;
while (playerWins < 5 && computerWins < 5 ) {
if (humanVsMachine === 'player') {
playerWins += 1;
} else if (humanVsMachine === 'computer') {
computerWins += 1;
}
// return [playerWins, computerWins]; moving code to below
}
return [playerWins, computerWins]; // moved return outside the loop here
}
console.log(playToFive());
Allow me to add that spacing your code helps a lot, it's a little bit 'vertical' looking with the closing brackets. Note how spacing on the above helps to visually identify things like this :)

I just want to call some loop when give the condition. but it was error

var game1 = prompt("Welcome to FuzzBUzz", "Let's try now GO");
for (var i= 1; i<21; i++){
if(i / 3){
console.log("Fizz");
}
else if (i/ 5){
console.log("Buzz");
}
else if ((i / 3) && (i / 5)){
console.log("FizzBuzz");
}
else{
console.log("choose what you want");
}
};
Your if statements are not conditional. You are just dividing i by a number. If you want to check if it's divisible, use the modulus and check for 0.
if(i%3 == 0){ //if i can be divided evenly by 3, then do something
do something
}
Conditions in if statements need to evaluate to a result which tells the if statement whether or not to execute the block; if the condition holds true the block is executed and vice versa. Change your condition statements to be statements which can be evaluated using comparison operators like: ==, !=, >, >= and you will be successful.

Calculating and displaying the result depending on the score

In the following JavaScript code you answer both questions and then you will get a specific answer based on your score.
Let's say, you choose Yes a lot for the first question and Chocolate for the second question, you will score 8 points and instead of displaying the number 8 I would like to display a comment. That's why I have created an if loop, but for some reason the javascript code is displaying nothing, any suggestions for a solutions?
By the way you can find the code in the following link:
http://jsfiddle.net/9N5ZV/
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Your condition syntax is wrong, and you use variables out of scope.
Demo
function getTotal()
{
var totalScore = getScoreCake() + getScoreChoco();
document.getElementById('result').innerHTML =
//"Your total score is: "+totalScore;
getComment(totalScore);
}
function getComment(score)
{
if (score <=2)
return healthy;
else if(score >= 3 && score <=6)
return average;
else
return unhealthy;
}
You need an else if
if (totalScore <=2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Also, use the console! You'll see:
Uncaught SyntaxError: Unexpected number
This was due to the else (expr) clause, it's else if
You conditional statement has errors. Should be:
if (totalScore <= 2) {
calculate = healthy;
} else if (totalScore >= 3 && totalScore <= 6) {
calculate = average;
} else {
calculate = unhealthy;
}
Here is an updated jsFiddle.
EDIT:
You are not calling getComment function. Try the one below to see how you can output the string.
http://jsfiddle.net/9N5ZV/5/

Javascript if statement not executing 2nd parameter

I have a var that is either 1 or 0, if it's 1 the page should go to cnn.com if it's 0 it should go to google.com. Problem is, when it's 1 or 0 it always goes to google.com. Check out the running version at http://jsbin.com/ucovef/7 Thanks in advance
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random()
}
function check_random(){
if (randomnumber = 0){
this.location.href ="http://www.cnn.com";
}
if (randomnumber = 1){
this.location.href="http://www.google.com";
}
}
You need:
if (randomnumber == 0)
And:
if (randomnumber == 1)
Expressions randomnumber = 0 and randomnumber = 1 are assignment expressions that assign numbers 0 and 1 to the variables, despite them being inside an if conditional statement.
So, it always goes to google.com because everything not equal to 0 is a true expression in JavaScript.
You have to use == to make a check. = sets the value instead of evaluating it. I would also suggest passing the random number to the function.
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('random').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(randomnumber){
if (randomnumber == 0){
this.location.href ="http://www.cnn.com";
}
else if(randomnumber == 1){
this.location.href="http://www.google.com";
}
}
You must use == not = !!!!!!!!!!!!!!!!
Ben, you are using local variable from random in check_random. This won't work. Try this
function random(){
var randomnumber=Math.floor(Math.random()*2)
document.getElementById('randomnumber').innerHTML=(randomnumber);
check_random(randomnumber)
}
function check_random(n){
if (n == 0){
this.location.href ="http://www.cnn.com";
}
if (n == 1){
this.location.href="http://www.google.com";
}
}

Categories

Resources