Here I am getting true. I should get a false value instead.
let x = 2021;
let y = 12;
getMn = new Date(x,y).getMonth()
const date = new Date();
let xyz = (date.getMonth() <= getMn ) ? false : true;
console.log(xyz);
So here i dont understand why i am getting true value if i check in console by place 11 directly instead of date.getMonth
( 11 <= 0 ? false : true
) then I am getting false then my question is why its returning me different results both the scenario
CodePudding user response:
Lets debug this by adding the following line:
console.log(getMn, date.getMonth());
This yields 0 11
. The 0
is caused by the months being 0-indexed, so we'll need an 11
for December.
One more note, instead off () ? false : true
we can simply revert the expressions with an !
:
let x = 2021;
let y = 11; // December
getMn = new Date(x,y).getMonth()
const date = new Date();
let xyz = !(date.getMonth() <= getMn )
console.log(getMn, date.getMonth());
console.log(xyz);
CodePudding user response:
Your expression is really 11 <= 0 ? false : true
.
Since obviously 11 is not less or equal to 0 the latter part gets evaluated (after :
), and so you get true
.
BTW, the expression 11 <= 0 ? false : true
is the same as 11 > 0
without any ternary.
CodePudding user response:
Well date.getMonth() is zero-based according to the documentation here -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
So when you do date.getMonth() <= 11 ? false : true the condition is true so it returns false. If the condition is false then it will return true. And the getMn.getMonth() is like so 11 <= 0 which is false so it returns true. The ternary operator is like so: if the condition is true you return the condition after the "?" and if it is false you return the condition after the ":". Check this about the ternary https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator