2

Both result in "undefined"... For Example

var a;
typeof blablabl; //"undefined";
typeof a; //"undefined";

What is the default way to check if variable is undefined or if variable hasn't been declared;

var a = a || 3;

Only works if variable already exists in the scope.

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168

3 Answers3

2

If you can hard code variable names you can test for the initialization of some variable (e.g. b) without modifying it's value in the following way,

(function () {
    "use strict";
    var foo;
    try {
        foo = b;
        console.log('b', ' is initialised');
    } catch(e) {
        if (e instanceof ReferenceError)
            console.log('b', ' is not initialised');
    }
}());

Also note that the following throws no errors

(function () {
    "use strict";
    var foo;
    var foo;
}());

So if you're "not sure", just var it again.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • That trick without assigning testee a value is smart, indeed! Is there an option to get the current scope and test if it `hasOwnProperty()` or alike? – Serge Nov 19 '15 at 15:30
  • @Serge well you could `.call(this)` but I don't see where a problem is with testing for the existence of properties, we already have lots of ways to do that. – Paul S. Nov 19 '15 at 15:31
2

Just tested my suggestion, seems to work:

"use strict";
try {
  b = 3;
} catch(e) {
  console.log("Caught it:", e);
  // Caught it: ReferenceError: assignment to undeclared variable b
}
Serge
  • 1,531
  • 2
  • 21
  • 44
1

(a === undefined) will return true if a has not been defined.

(a == undefined) will return true if a has not been defined or if a equals null.

If you want to check if a variable exists, you could check the scope of this if applicable:

var exists = (this.hasOwnProperty('a'))? 'a exists in the current scope' : 'a doesnt exist';

Shilly
  • 8,511
  • 1
  • 18
  • 24