Home > Net >  Trying to get this code to display a greeting when user enters certain hours in a prompt
Trying to get this code to display a greeting when user enters certain hours in a prompt

Time:10-16

This is the code I have written so far.

<!DOCTYPE html>
<html>
<body>
<script>
{
let hourNow = prompt("please enter the hour based on 24hr clock");
var greeting;

if(hourNow = 6 && hourNow<=9){
greeting = 'Brreakfast is served.';
} else if (hourNow >= 11 && hourNow <=13){
greeting = 'Time for lunch.';
} else if (hourNow = 17 && hourNow >=20){
greeting = 'Time for dinner';
}else{
greeting = 'You will have to wait or get a snack'
}
}
document.write('<h3>'   greeting   '</h3>');

</script>
</body>

</html>

The code works and it doesn't work It seems to work ok for breakfast if you input 9. All other hours it is saying sorry you have to wait or get a snack.

CodePudding user response:

use double equal (comparison) instead of single equal (assign)

also you don't need to use >= while you already have used ==. it's redundent

also I assumed some cases here is a fixed answer

{
let hourNow = prompt("please enter the hour based on 24hr clock");
var greeting;

if(hourNow >= 6 && hourNow<=9){
greeting = 'Brreakfast is served.';
} else if (hourNow >= 11 && hourNow <=13){
greeting = 'Time for lunch.';
} else if (hourNow >= 17 && hourNow <=20){
greeting = 'Time for dinner';
}else{
greeting = 'You will have to wait or get a snack'
}
}

CodePudding user response:

if(hourNow = 6 && hourNow<=9){

always returns true so you get the result you're seeing.

You want hourNow == 6 not hourNow = 6

Thanks to @Michel for pointing out that the same issue applies here:

} else if (hourNow = 17 && hourNow >=20){
  • Related