Jordan Davis
Jordan Davis

Reputation: 1520

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?

Upvotes: 1

Views: 12511

Answers (3)

Parameswaran N
Parameswaran N

Reputation: 141

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

another way

Upvotes: 7

Wainage
Wainage

Reputation: 5412

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

Useful to check function parameters

Upvotes: 8

Joe
Joe

Reputation: 82594

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

Upvotes: 1

Related Questions