Monday, May 20, 2024
38
rated 0 times [  41] [ 3]  / answers: 1 / hits: 22577  / 7 Years ago, fri, june 30, 2017, 12:00:00

I'm trying to get this Javascript to do something if the day of the week matches any of the days listed in my statement, as well as restricting it to between 17:00 and 19:00 hours, but the OR operator is not working as I expected, I'm new to JS and I'm wondering if I'm misunderstanding the use of this operator. If I were to list a value for just one day of the week, instead of 3 like in my example, the code works as I'd hoped.



var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( dayOfWeek == 4 || 5 || 6 && hour >= 17 && hour < 19 ){
// do stuff
} else {
// do other stuff
}

More From » if-statement

 Answers
52

In this case, you better use a range check, because you need only two comparisons against of three or more - and it is better maintanable, just to change a value, if necessary.



if (dayOfWeek >= 4 && dayOfWeek <= 6 && hour >= 17 && hour < 19) {


The right OR conditions needs parenthesis, because of the precedence of && over ||



if ((dayOfWeek == 4 || dayOfWeek == 5 || dayOfWeek == 6) && hour >= 17 && hour < 19 ) {

[#57260] Tuesday, June 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;