1

I am trying to check if the firstday is equal to five or 6, in both cases if totalDays is equal to 31 then do something, for that purpose which statement is correct?

Code 1:

if (firstday > 5 || firstday > 6 && totalDays == 31){}

Code 2:

if (firstday > 5 && totalDays == 31 || firstday > 6 && totalDays == 31) { }
Sunil B N
  • 4,159
  • 1
  • 31
  • 52
Mohsin
  • 179
  • 4
  • 13
  • i think you dont need `|| firstday > 6` in 1st statement – Mahi Nov 18 '16 at 06:37
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence – Mahi Nov 18 '16 at 06:39
  • Try to iterate your conditions in english and use `()` to group conditions. In you statement *firstday has to equal to 5 or 6, but in both case, totalDays must be 31*. So solve first part: `firstday === 5 || firstday === 6`. your second condition is `totalDays===31`. But this has to happen in case of both, so this becomes, `(firstday === 5 || firstday === 6) && totalDays===31` – Rajesh Nov 18 '16 at 06:45

5 Answers5

6

This is the correct answer:

if ((firstday == 5 || firstday == 6) && totalDays == 31){
    //Do something
}
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
0

Both are wrong you need to use == operator for it.

if ((firstday == 5 || firstday == 6) && totalDays == 31){}
priya_singh
  • 2,478
  • 1
  • 14
  • 32
0
if ((firstday == 5 || firstday == 6) && totalDays == 31){}

Here the expression inside the inner most parenthesis(firstday == 5 || firstday == 6) is executed first. Based on the value the remaining expression is evaluated, if the above expression return false the remaining expression is not evaluated since the false&&(true||false) anyways false.

Ashok kumar
  • 544
  • 1
  • 5
  • 21
0

First condition: It returns True, if firstday is 5 OR 6.. AND TotalDays is 31.

if ((firstday == 5 || firstday == 6) && totalDays == 31){ }
Vikrant
  • 4,920
  • 17
  • 48
  • 72
0

Both your logic work, but you mentioned in your question that "if the first day is equal to five or 6", so I would suggest that you use '==' instead of '>'. The latter will accept any value above 5, which does not match what you want.

Either one of the following lines will achieve your desired outcome.

if (firstday == 5 || firstday == 6 && totaldays == 31) {}

OR

if (firstday == 5 && totalDays == 31 || firstday == 6 && totalDays == 31) { }
Sunil B N
  • 4,159
  • 1
  • 31
  • 52
timothyjoseph
  • 91
  • 2
  • 9