value - JavaScript check if variable exists(is defined/initialized)

javascript set variable to undefined (19)

Check if an object hasOwnProperty()

An alternative to the plethora of typeof answers, is the use of hasOwnProperty() which of course checks if an object (pretty much everything in JS) has a property i.e. a variable (amongst other things).

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.

Every object descended from Object inherits the hasOwnProperty() method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

// Globally established (therefore) properties of window
var foo = "whatever", // string
    bar = false,      // bool
    baz;              // undefined
// window.qux does not exist

console.log( [
    window.hasOwnProperty( "foo" ),             // true
    window.hasOwnProperty( "bar" ),             // true
    window.hasOwnProperty( "baz" ),             // true
    window.hasOwnProperty( "qux" ),             // false
    { foo: [], bar: 0 }.hasOwnProperty( "bar" ) // true
] );

What's great about hasOwnProperty() is that in calling it, we don't use a variable that might as yet be undefined - which of course is half the problem in the first place.

Although not always the perfect or ideal solution, in certain circumstances, it's just the job!

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

if (elem) { // or !elem


if (typeof(elem) !== 'undefined') {


if (elem != null) {

How to check if a variable exists

This is a pretty bulletproof solution for testing if a variable exists and has been initialized :

var setOrNot = typeof variable !== typeof undefined;

It is most commonly used in combination with a ternary operator to set a default in case a certain variable has not been initialized :

var dark = typeof darkColor !== typeof undefined ? darkColor : "black";

Problems with encapsulation

Unfortunately, you cannot simply encapsulate your check in a function.

You might think of doing something like this :

function isset(variable) {
    return typeof variable !== typeof undefined;

However, this will produce a reference error if you're calling eg. isset(foo) and variable foo has not been defined, because you cannot pass along a non-existing variable to a function :

Uncaught ReferenceError: foo is not defined

Testing whether function parameters are undefined

While our isset function cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :

var a = '5';

var test = function(x, y) {


// ------------

Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.

A bit more functional and easy to use:

function exist(obj)
    return (typeof obj !== 'undefined');

The function will return true if exist, else false if does not exist.

I can't see this in the above answers, so I'll suggest it here, I guess.

function isDefined(x) { return !!x }

if( isDefined(x) ) {
    //The variable is defined

!x will return true iff x is either null or undefined, so !!x will only return true iff x is neither undefined nor null.

I realise that this also accounts for the null case, but here's fair warning about that.

If you want defined block to do something then use this

if (typeof variable !== 'undefined') {
    // the variable is defined

If you want undefined block to do something or assign or define the variable then use this

if (typeof variable === 'undefined') {
    // the variable is undefined

In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:

if (typeof v === "undefined") {
   // no variable "v" is defined in the current scope
   // *or* some variable v exists and has been assigned the value undefined
} else {
   // some variable (global or local) "v" is defined in the current scope
   // *and* it contains a value other than undefined

That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):

if ("v" in window) {
   // global variable v is defined
} else {
   // global variable v is not defined

This, of course, assumes you are running in a browser (where window is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window is stylistically consistent with using to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.

In the majority of cases you would use:

elem != null

Unlike a simple if (elem), it allows 0, false, NaN and '', but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.

The other checks are not incorrect either, they just have different uses:

  • if (elem): can be used if elem is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

  • typeof elem == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.

    • This is the only check that won't throw an error if elem is not declared (i.e. no var statement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.

Also useful is a strict comparison against undefined:

if (elem === undefined) ...

However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:

var undefined; // really undefined
if (elem === undefined) ...


(function (undefined) {
    if (elem === undefined) ...

A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.

In the particular situation outlined in the question,

typeof window.console === "undefined"

is identical to

window.console === undefined

I prefer the latter since it's shorter.

Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.

@BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.

It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:

if (typeof(jQuery) != "undefined")

(No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.

function sayHello(name) {
    if (name) return "Hello, " + name;
    else return "Hello unknown person";
sayHello(); // => "Hello unknown person"

It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined is a special value which will be the default value of unassigned variables.

var _undefined;
var _null = null;

alert(_undefined == _null);
alert(_undefined === _null);

Null is a value in JavaScript and typeof null returns "object"

Therefore, accepted answer will not work if you pass null values. If you pass null values, you need to add an extra check for null values:

if ((typeof variable !== "undefined") && (variable !== null))  
   // the variable is defined and not null

The typeof operator will check if the variable is really undefined.

if (typeof variable === 'undefined') {
    // variable is undefined

The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null

For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

The most robust 'is it defined' check is with typeof

if (typeof elem === 'undefined')

If you are just checking for a defined variable to assign a default, for an easy to read one liner you can often do this:

elem = elem || defaultElem;

It's often fine to use, see: Idiomatic way to set default value in javascript

There is also this one liner using the typeof keyword:

elem = (typeof elem === 'undefined') ? defaultElem : elem;

There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.

var values = typeof variable !== 'undefined' ? variable : '';

Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.

If you wanted to check variable shouldn't be undefined or null. Then perform below check.

When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.

var values = variable ? variable : '';

To check if a variable has been declared/set I did this dirty trick.

I haven't found a way to extract the code to a function, even with eval.

"use strict";

// var someVar;

var declared;
try {
  declared = true;
} catch(e) {
  declared = false;

if (declared) {
  console.log("someVar is declared; now has the value: " + someVar);
} else {
  console.log("someVar is not declared");

To contribute to the debate, if I know the variable should be a string or an object I always prefer if (!variable), so checking if its falsy. This can bring to more clean code so that, for example:

if (typeof data !== "undefined" && typeof data.url === "undefined") {
    var message = 'Error receiving response';
    if (typeof data.error !== "undefined") {
        message = data.error;
    } else if (typeof data.message !== "undefined") {
        message = data.message;

..could be reduced to:

if (data && !data.url) {
  var message = data.error || data.message || 'Error receiving response';

You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {
    // the variable is defined


if( typeof foo !== 'undefined' ) { 



if( foo instanceof Array ) { 


if (typeof console != "undefined") {    

Or better

if ((typeof console == "object") && (typeof console.profile == "function")) {    

Works in all browsers