user2303307
user2303307

Reputation: 11

if (a) {} throws uncaughtReferenceError

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

Answers (3)

Jonathan Lonowski
Jonathan Lonowski

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

ghost
ghost

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

Ozerich
Ozerich

Reputation: 2000

if (typeof a === 'undefined'){
  // variable is not available and you can write a = {}
}

but a = a || {} is shortly

Upvotes: 2

Related Questions