Reputation: 10131
for example, my code below
(function ($) {
window.FOO || (FOO = {});
}(jQuery));
caused jshint error:
Expected an assignment or function call and instead saw an expression.
Are there any better way to write my above code?
i.e. if FOO
is not defined in global window scope, init it as {}
Upvotes: 1
Views: 182
Reputation: 128786
Update: From comments:
I've updated the code above. I want the FOO in the global scope, i.e. window.
For that you can just set window.FOO
instead:
window.FOO = window.FOO || {};
Here if window.FOO
already exists its value will remain unchanged, otherwise window.FOO
will be set to an empty object.
Old answer:
You need to declare the variable using var
:
var FOO = window.FOO || {};
This will set the FOO
variable to window.FOO
if that exists or an empty object if not.
var FOO = window.FOO || {};
console.log(FOO);
> Object {}
window.FOO = "Hello, world!";
var FOO = window.FOO || {};
console.log(FOO);
> "Hello, world!"
Upvotes: 2