Reputation:
This works great:
var x = x || 3 //x = 3
This does not:
let y = y || 4 //Uncaught ReferenceError: y is not defined
My IDE (webstorm) warns me on all usages of var
, so I've been trying to avoid it (I assume this is current best practice). So what is the correct way to instantiate a variable only if it doesn't already exist?
Use Case: I am dynamically loading "widgets", which include an HTML, Javascript and CSS file. Each Javascript file has its own closure (widget = (function() {})()
). I need to be able to "reload" these.
Upvotes: 2
Views: 84
Reputation: 163262
Declare y
first, then set its value in a different statement.
let y;
y = y || 4;
You can't declare with let
or const
multiple times, so you'll do that let
declaration somewhere at the top of the scope you want it in.
Upvotes: 1