Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript current date with an argument

Tags:

javascript

Pretty straightforward, I have this:

var optionalDate;
var date = new Date(optionalDate || null);

What I want to do is, create a date with the optional date if available, if not, create today's date. If I pass null to the function (as it is in the example), it will create Wed Dec 31 1969, If I pass "", won't work, and if I leave blank, also won't work..

Is there any parameter that can be used to get today's date (I know the absence of parameters would work, but wouldn't be valid in the || operation) . Sorry for the simple question, but I couldn't find the answer to this.

like image 585
sigmaxf Avatar asked Jan 24 '26 09:01

sigmaxf


1 Answers

Use a ternary expression:

var date = optionalDate ? new Date(optionalDate) : new Date();
like image 85
Barmar Avatar answered Jan 25 '26 22:01

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!