Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ternary always returning true condition? But should not be

Hello I am troubleshooting code,

I’m new to javascript and have no idea why the below ternary is always returning the true condition. I do not want to add one month if I have a null or empty string. I want to simply make the variable a false boolean.

But I always get today’s date + a month.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I missing something here?

(Foo.Bar.limp?.bizkit?.rollin !== null && !Foo.Bar.limp?.bizkit?.rollin !=="" ? moment(Foo.Bar.limp?.bizkit?.rollin).add(1, "months").toISOString() : false)

>Solution :

Maybe, you’re missing the validation of undefined. Right now you’re using strict equal instead of just equal, you can try:

Option 1

Boolean(Foo.Bar.limp?.bizkit?.rollin) ? moment(Foo.Bar.limp?.bizkit?.rollin).add(1, "months").toISOString() : false)

In, this way you will accept anything which is not empty, null, undefined
P.S. you can use: !!value instead of Boolea(value) (because in JS we have the falsy value concept

Option 2:

(Foo.Bar.limp?.bizkit?.rollin != null && !Foo.Bar.limp?.bizkit?.rollin != '' ? moment(Foo.Bar.limp?.bizkit?.rollin).add(1, "months").toISOString() : false)

It’s what you have with more flexibility, one more time based on falsy values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading