I was experimenting around with some javascript in my browser console and and not sure exactly why this doesn't work. The following code in the console and jsfiddle on my attempts throws the error: Uncaught ReferenceError: foo is not defined
foo = foo || {};
The way i interpret this is: if foo of the global object (window in this case) doesn't exist, then create it as an empty object.
Alternatively, the code window.foo = window.foo || {}
; works as I would expect. Assigning a value beforehand to foo with foo = 'bar'
makes the original statement work when running afterwards as well.
You have to check whether foo
is defined first:
foo = typeof foo !== 'undefined' ? foo : {};
It may be a little unintuitive, but there is a difference between being undefined and having a value of undefined
(which window.foo
returns when window
doesn't have a foo
property).
A better way would be to add the var
keyword:
var foo = foo || {};
Which works because JavaScript hoists the variable declaration up to the top of the current scope, declaring foo
and giving it a value of undefined
:
var foo;
foo = foo || {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With