shorthand if/else variable exists

12k Views Asked by At

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?

3

There are 3 best solutions below

1
Wainage On BEST ANSWER

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

Useful to check function parameters

4
Joe On

You can use Object Notation:

// In the global scope window is this
this['year'] = this['year'] ? year : (new Date).getFullYear();
console.log(year);

or perhaps better use typeof

year = (typeof year === "undefined") ? (new Date()).getFullYear() : year
1
Parameswaran N On
year = year ?? new Date().getFullYear();

another way