Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shorthand if/else variable exists

I'm simply running a function which checks if the variable year is set if not then set it new Date().getFullYear().

The error I get:

Uncaught ReferenceError: year is not defined

year = (year) ? year : new Date().getFullYear();
console.log(year);

Why can't I check if year exists and if not set it?

like image 673
Jordan Davis Avatar asked Apr 26 '26 01:04

Jordan Davis


2 Answers

year = year || new Date().getFullYear();

Useful to check function parameters

like image 87
Wainage Avatar answered Apr 27 '26 14:04

Wainage


year = year ?? new Date().getFullYear();

another way

like image 27
Parameswaran N Avatar answered Apr 27 '26 14:04

Parameswaran N