Reputation: 11
I need to be able to check if a variable exists (if if it doesn't assign it to {}) without throwing an error in javascript. When I try this code
if (a) {}
it throws uncaughtReferenceError
What I really want to do is something like this without throwing an error:
a = a || {}
or maybe it looks like this
if (a) { a = {} }
Upvotes: 1
Views: 59
Reputation: 123533
If a
is a global, you can use the global object to avoid the error. In browsers, that object is window
:
window.a = window.a || {};
Or, as Ozerich suggested, you can use typeof
, which won't throw reference errors:
if (typeof a === 'undefined') {
a = {};
}
Upvotes: 2
Reputation: 769
a = a || {}
simply won't work, because a
is not defined. But you can use typeof
to check if it exists or not.
a = (typeof(a) === 'undefined' ? {} : a);
Upvotes: 0
Reputation: 2000
if (typeof a === 'undefined'){
// variable is not available and you can write a = {}
}
but a = a || {}
is shortly
Upvotes: 2