Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable has been declared, although uninitialized?

Tags:

javascript

How to check if a JavaScript variable has actually been declared?

This solution doesn't work in my case:

JavaScript check if variable exists (is defined/initialized)

Example:

(function(){
    var abc;
    alert(typeof abc === 'undefined') // true
})();

Same as:

(function(){
    alert(typeof abc === 'undefined') // true
})();

It produces true in both cases. I could do this:

(function(){
    var abc;

    var isDefined = false;
    try { isDefined = abc || !abc; }
    catch(e) {}
    alert(isDefined); // true
})();

It works, but I'm looking for anything better that this, x-browsers.

EDIT: I want to use it in a piece of dynamic code which runs via eval and checks if a certain variable exists in either local or global scope.

like image 259
avo Avatar asked Nov 02 '22 02:11

avo


1 Answers

This question has been asked many times, the answer is "you can't" (other than using try..catch as in the OP).

You can check for properties of an object using in or hasOwnProperty, however both those require that you can access the object that you wish to test. Variables belong to a variable object (ES 3) or environment record (ES 5) of an execution context, and they aren't accessible so you can't check their properties.

The special case is the global object, because global variables (i.e. properties of the global environment record) are made properties of the global object, so you can do:

var global = this;
var foo;

// Declared but not initialised
foo in global // true
global.hasOwnProperty('foo'); // true

// Not declared or initialised
bar in global  // error
global.hasOwnProperty('bar'); // true

However, the hasOwnProperty method is not supported on the global object for versions of IE < 9.

like image 55
RobG Avatar answered Nov 10 '22 01:11

RobG