Home > Software engineering >  Learning about conditional statements for JS; question about an exercise
Learning about conditional statements for JS; question about an exercise

Time:12-29

I'm pretty new to coding and I've been having a hard time with making the concept of conditional statements stick--but I also haven't practiced consistently in weeks so hopefully I can get the hang of things with consistent practice..

I'm watching a YouTube video to review if else statements, and the exercise in the video asked me to enter code to communicate this:

// Hour
// If hour is between 6am and 12pm: Good morning!
// If it is between 12pm and 6pm: Good afternoon!
// Otherwise: Good evening!

I tried to do it myself before revealing the answer and came up with this:

if (hour >= 6 && < 12)
console.log('Good morning!')
else if (???)
console.log('Good afternoon!')
else
console.log('Good evening!')

I got everything right except for the 'Good afternoon' condition of course, and according to the video, the answer is

if (hour >= 6 && < 12)
console.log('Good morning!')
else if (hour >= 12 && hour < 18)
console.log('Good afternoon!')
else
console.log('Good evening!'

After seeing the answer, I understand why the 18 is there because it's 18 out of 24 hours...but do I not have to disclose that I'm referring to time/24 hours somehow? How would the computer know that I'm using time as a metric? Are there other cases/scenarios in which I should expect for my computer to know which metric I'm using, like if I'm referring to Kelvin or Celsius, for example? Does the 'hour' variable in line 1 take care of this issue? I could be overthinking it but I just need clarification on how it works.

I honestly had no idea where to start tbh..I was thinking that I had to incorporate a nested loop somehow?

CodePudding user response:

To the computer it doesn't matter what the variable is; just that it's a number. It's up to you to make it 24-hour time when you assign it (See the answer below for how). You could name the variable whatever you like and it would work just the same.

CodePudding user response:

@Ariana in coding there is one rule

** Keep it simple and smart

you know the timezone you know when it is evening and when it's afternoon and so on.

you get to have hours from any date and time in JS using eg:

let date = new Date();
let hours = date.getHours();

After this, you can add your logic to determine the times of the day.

Hope this answers your question :) :)

  • Related