I am not so into JavaScript\TypeScript and I am finding the following problem with this code:
let timeStampAsDate = new Date();
let term = "2021";
console.log("XXX: ", timeStampAsDate?.getFullYear().toString().toLowerCase().includes(term) && timeStampAsDate != null);
let timeStampAsDate2 = undefined;
console.log("XXX: ", timeStampAsDate2?.getFullYear().toString().toLowerCase().includes(term) && timeStampAsDate2 != null);
Here you can run the code and see the output
I'll try to explain what is my problem:
As you can see in the previous code I have 2 different use cases, in the first one I first create a Date
object and then I have a term
representing an year that will be later used in a search (basically I am searching the inserted term representing a year into the year field of my date):
let timeStampAsDate = new Date();
let term = "2021";
console.log("XXX: ", timeStampAsDate?.getFullYear().toString().toLowerCase().includes(term) && timeStampAsDate != null);
If it is retrieved it print the Boolean value true. It works fine.
The second case is related to the use case where I have no date (this because in my application I can have undefined field of this type, because these data came from a Firebase database and can be not present):
let timeStampAsDate2 = undefined;
console.log("XXX: ", timeStampAsDate2?.getFullYear().toString().toLowerCase().includes(term) && timeStampAsDate2 != null);
Here I am not obtaining a Boolean value but in my console I am obtaining this output:
XXX: undefined
My idea is that having this && timeStampAsDate2 != null
into my confition the final value have to be false but I discovered that in JavaScript\TypeScript an expression like this:
console.log(undefined && false)
give undefined as result and not false.
What can be a nice way to change my original condition in such a way that it is evaluated as false and not as undefined in the case that my timeStampAsDate2
is undefined?