How to get the result of If/ If else statement - javascript

I don't know if I'm overseeing it or what, but I don't know how to get the result of an else if statement, for example, I have this code that I have been practicing:
In this case, the result would be "It's warm!", what I'd like to do is to create a code that would depend on the result, but the result it's not a variable, so how do I create a code responding to what was logged? for example if it logged: "It's warm!" I want to add something like "Turn on the AC." or "Turn on the heater" or something else. How do I do it?
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!");
} else if (temperature < 24) {
console.log ("It's cold!");
} else {
console.log ("It's cool!");

You could just save it as a variable:
let temperature = 36;
const isCold = temperature < 24;
const isWarm = temperature > 24;
if (isWarm) {
console.log("It's warm!");
} else if (isCold) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
if (isWarm) {
console.log("Turn on the A/C!");
}

you can set your code in the expresion block that are defined with {} after the if condition..
As example:
let temperature = 36;
if (temperature > 24) {
console.log("It's warm!");
console.log("Turn on the AC.");
// You can write coode base in this condition as much you want
// or you can call another function
} else if (temperature < 24) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}

Not quite sure what you mean, but if you want to output the temperature:
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!", temperature, "degrees");
} else if (temperature < 24) {
console.log ("It's cold!", temperature, "degrees");
} else {
console.log ("It's cool!", temperature, "degrees);

Put the result into a variable.
let temperature = 36;
let result = '';
if (temperature > 24) {
result = "It's warm!";
} else if (temperature < 24) {
result = "It's cold!";
} else {
result = "It's cool!";
}
console.log (result);

You can set a variable in a function - pass the temperature into the fucntion and output the result - note the use of the switch statement that compares the inputted temp to the conditions and update the result string. This is what switch statements are for - to provide an alternative to nested or complex if else statments.
function setTemperature(temp){
let result = "It's ";
switch (true) {
case temp > 24:
result += "warm!";
break;
case temp > 12:
result += "cool!";
break;
default:
result += "cold!";
}
return result;
}
console.log( setTemperature(36)); // gives "It's warm!"
console.log( setTemperature(16)); // It's cool!
console.log( setTemperature(6)); //It's cold!

You can make a function like so:
let temperature = 36;
function myFunct(temp){ // "myFunct" can be anything
if (temp > 24) {
return "It's warm!";
} else if (temp < 24) {
return "It's cold!";
} else {
return "It's cool!";
}
}
var t = myFunct(temperature); // get whether it's warm, cold, or cool
console.log(t); // tell the user if it's warm, cold, or cool
// do something!
if(t === "It's warm!"){
// run something here if it's warm
} else if (t === "It's cold!"){
// run something here if it's cold
} else {
// run something here if it's cool
}
Though you could just run something inside the function or original if statement instead.
Hope this helped!

Related

conditional statement if value is greater or less then show error

I am trying to display a warning message if the temperature is higher then 40 or above - 10
but is not working.
I read some websites and in StackOverflow I found this Switch statement for greater-than/less-than to try to solve the problem but I still couldn't find a solution for what might be happening.
Can you help me out?
Many thanks.
function Celsius(kelvin) {
let celsiusTemp = Math.round(kelvin - 273.15);
if (celsiusTemp > 35) {
console.log('too hot, use sunscreen ')
} else
if (celsiusTemp < 5) {
console.log('too cold, get warm ')
} else {
return celsiusTemp + `°C`;
}
};
Celsius(kelvin) {
let celsiusTemp = Math.round(kelvin - 273.15);
if (celsiusTemp < 35 || celsiusTemp > 5) {
return celsiusTemp + `°C`;
}
if (celsiusTemp > 35) {
return celsiusTemp + `°C, too hot, use sunscreen`;
}
if (celsiusTemp < 5) {
return celsiusTemp + `°C,too cold, get warm`;
}
}
//call method Celsius(298) here like this
console.log(this.Celsius(298));
//or
console.log(Celsius(298));

How do i turn 2 prompt answers into 1 result for a concatenation

I need to create javascript that asks what the temperature is like then kick out a string based on the temperature then ask what type of event they're going to and kick out a string based on their answer then put both of those answers into 1 result and put it into my concatenation
let temp = "What is the temperature today?";
let event = "What type of event are you going to?";
let result2 = {
casual: "something comfy",
semiformal: "a polo",
formal: "a suit",
}
let tempFahr = prompt(temp);
let eventType = prompt(event);
let result1 = "";
let result = result1 + result2;
console.log(tempFahr);
console.log(eventType);
if (eventType == result2.casual) {
let result2 = "something comfy";
} else if (eventType == result2.semiformal) {
let result2 = "a polo";
} else if (eventType == result2.formal) {
let result2 = "a suit";
}
if(tempFahr <= 54) {
console.log("a coat")
} else if(tempFahr >=55 && 70) {
console.log("a jacket")
} else if(tempFahr > 70) {
console.log("no jacket")
}
console.log(`since it is ${tempFahr} degrees and you are going to a ${eventType} event, you should wear ${result}`);
----This is what's expected----
“Since it is 33 degrees and you are going to a formal event, you should wear a suit
and coat.
----This is the actual output----
66 script.js:15
casual script.js:36
a jacket script.js:45
since it is 66 degrees and you are going to a casual event, you should wear [object Object]
You seem to have confused a couple of concepts. First, for handling the event type, your first "result2" definition is essentially a table of resulting clothing. So the block
if (eventType == result2.casual) {
let result2 = "something comfy";
} else if (eventType == result2.semiformal) {
let result2 = "a polo";
} else if (eventType == result2.formal) {
let result2 = "a suit";
}
can be shortened to
let clothing = result2[eventType];
As it is now, it is comparing the event type to the clothing types. BTW, you'd probably want a bit of error handling on that as well.
Secondly, for the temperature block, you are logging the outcome, but not saving it in a variable. So
if(tempFahr <= 54) {
console.log("a coat")
} else if(tempFahr >=55 && 70) {
console.log("a jacket")
} else if(tempFahr > 70) {
console.log("no jacket")
}
should be something like
if(tempFahr <= 54) {
jacket = "a coat";
} else if(tempFahr >=55 && tempFahr <= 70) {
jacket = "a jacket";
} else if(tempFahr > 70) {
jacket = "no jacket";
}
And then your final output statement will need to be changed to match the new variable names I've chosen. I changed them because your existing naming was a bit confused.

not converting the int into a string on if statement

I am trying to convert an int into a str using a if loop! here is my logiv. What is it that I am doing wrong ? Any ideas ?
var waitTime = parseInt("53");
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
console.log(waitTime);
I keep getting
Your code looks mostly correct, including your usage of parseInt, but perhaps you are mixing your return statements with console.log statements?
var waitTime = parseInt("53");
if (waitTime > 20) {
console.log('a lot of time'); // use console.log rather than return
} else if (waitTime < 20) {
console.log('we can wait'); // use console.log rather than return
}
console.log(waitTime);
http://jsbin.com/kebagodura/edit?js,console,output
Alternatively (to Jonathan's answer), put the code in a function and then the returns would make sense. An improved version would see you passing in the wait time as an argument to the function.
function doIt(number) {
// Don't forget the radix on parseInt
var waitTime = parseInt(number, 10);
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
}
var result = doIt('53'); // a lot of time
var result = doIt('12'); // we can wait
DEMO
You could also do it this way- instead of "return" you can do this:
var waitTime = parseInt("53");
if (waitTime > 20) {
waitTime = 'a lot of time';
} else if (waitTime < 20) {
waitTime = 'we can wait';
}
console.log(waitTime);
You simply can do that this way, reassigning the variable values in the if/else clause:
var waitTime = parseInt("53");
if (waitTime > 20) {
waitTime = 'a lot of time';
} else if (waitTime <= 20) {
waitTime = 'we can wait';
}
console.log(waitTime);
You have an error in your code.
return 'a lot of time'
It is trying to return the text a lot of time from a function. but you never created a function so it will throw an error.
Closer to what you want:
function wait(waitTime) {
if (waitTime > 20) {
return 'a lot of time'
} else if (waitTime < 20) {
return 'we can wait'
}
}
console.log(wait(YOUR_WAIT_TIME_HERE));
EDIT You don't need the parseInt function at all. (ie: '25' > 20) implicitly casts '25' to a Number.

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;
}

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/

Categories

Resources