2017

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

or

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

or

if (elem != null) {
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
  • 9
    if you want to know whether `foo` is declared, either `typeof foo === 'undefined'` or `typeof foo === typeof undefined` –  Nov 22 '17 at 21:00
  • 2
    The highly upvoted answers don't work for variables that are declared but have the value `undefined`. The correct answer is this one: https://stackoverflow.com/a/36432729/772035 – Paul Jul 23 '19 at 22:50
  • 1
    @Paulpro, the version using `hasOwnProperty('bar')` doesn't have the same deficiencies as the others, but would require some adjustment for Node (replace `window` with `global`). – oligofren Sep 24 '19 at 06:17
  • @Paulpro Indeed, but as I was pondering that before you replied, I came to the conclusion that it's not really a practical problem. When you are dealing with block or function scoped variables, it's usually code you own or have write access to, so you'll have a runtime error in any case which is fixable. Whereas the usual problem with variables that has not beed defined (doesn't exist) usually lies in code outside of your control, so you need a way of detecting it. So it's the 80/20 solution. – oligofren Sep 24 '19 at 09:28

31 Answers31

3341

You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {
    // the variable is defined
}
meager
  • 209,754
  • 38
  • 307
  • 315
Jim Puls
  • 72,152
  • 10
  • 71
  • 78
  • 41
    This looks a good solution, but can you explain why this works? – Morgan Cheng Feb 06 '09 at 05:15
  • 47
    Actually, you should check that the object is what you need it to be. So that would be if( typeof console == 'object' ) { // variable is what I need it to be } – staticsan Feb 06 '09 at 06:14
  • 59
    @George IV: "just do `if( variable ) " -- um, no, that fails for false and 0. – Jason S May 13 '09 at 15:53
  • 18
    'if( variable )' also fails for testing for the existence of object properties. – scotts May 04 '10 at 22:40
  • 3
    @staticsan: That's a good thing to consider, but many times you really only care if it's defined. E.g. an API you're using defines a variable that you're using only to check if the API is loaded. – Jerph Jan 26 '11 at 16:31
  • 61
    @geowa4 Actually, that will throw an error if the variable is undefined. – kevinji Apr 19 '11 at 04:59
  • 5
    "if (typeof variable !== 'undefined') { // variable is not undefined }" is working for me too... thanks! – squarecandy Dec 06 '11 at 03:34
  • 2
    IE8 reported and error when I used: (typeof variable === "undefined" ), so I had to check for (typeof variable === "object" ) and that workded – b01 Feb 14 '12 at 19:08
  • 3
    @anyone Why is this preferable to `if (variable === undefined) {}` ? – temporary_user_name Jan 22 '14 at 03:02
  • 4
    See a couple answers further down. The value `undefined` is mutable. – Jim Puls Feb 10 '14 at 22:00
  • Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
  • As simple of JavaScript as this is I have NEVER used it but it serves my purpose beautifully. I have multiple .js files that run the same functions from a global js file, but only if a certain variable exists should certain functions run. Otherwise what I was doing is setting the variable to true or false and checking for that, but that would require me to address it on dozens of js files, so I needed another solution. Perfect! – Christine268 Aug 11 '15 at 16:23
  • @Jason S "um, no, that fails for false and 0" -- um, yes, if you know that your variable cannot be false or 0 :) – Ilker Cat Dec 16 '15 at 13:49
  • 4
    `typeof null; //=> "object"` – Thank you Jun 02 '16 at 12:44
  • 6
    This fails when variable is `null` – nikjohn Aug 29 '16 at 18:39
  • 2
    If you're on ES6 and your variable could be a const or let declared variable, there's a chance this code could fall in the temporal dead zone and throw ReferenceError. `if (typeof variable !== 'undefined') { // the variable is defined }; const variable = 'a';` => ReferenceError – tgf Jan 25 '18 at 02:18
  • 4
    This won't work with `let` or `const`. [Here's why](https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-not-hoisted-in-es6) – Adelin Jun 13 '18 at 11:18
  • Why does it not work with `typeof variable !== undefined` where the apostrophes is removed. Isn't `window.undefined = 'undefined'`? –  Jun 26 '19 at 17:19
  • 1
    This answer doesn't work. This is the only answer here that works: https://stackoverflow.com/a/36432729/772035 – Paul Jul 23 '19 at 22:49
  • you can use !!ArrayName. This will return false if array is undefined or null. In case of empty array it will return true. – Maddy Jul 28 '20 at 08:23
949

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?

Community
  • 1
  • 1
Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
  • 1
    @StevenPenny Check the timeline. The top answer was merged from [another question](http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript) after this answer was posted – Rob Dec 19 '16 at 23:25
  • Warning: This does not work for members of objects, if you try to access them using the dot notation as in `some_object.a_member`. – Zelphir Kaltstahl May 17 '17 at 08:19
  • this doesn't check if a variable exists, it checks its value type. You want to check if a variable it's been declared. @BrianKelley's answer is the right one. – dRamentol Nov 15 '18 at 19:12
  • why not just `variable != null` it seems to catch "undefined" variables just as well – Fuseteam Jul 08 '19 at 20:30
276

In many cases, using:

if (elem) { // or !elem

will do the job for you!... this will check these below cases:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example, if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.

I create the image below to show a quick brief of the answer:

undefined, null, etc

Alireza
  • 83,698
  • 19
  • 241
  • 152
  • Is the first case suitable when checking for an empty array too? – Thiago Yoithi Nov 29 '17 at 18:02
  • @ThiagoYoithi, yes, you need to pass Array.length in this case which is 0 when it's empty, like if (myArray.length) {...} – Alireza Nov 29 '17 at 22:17
  • Yeah, but I would like to know the behavior in this approach: let arrayVar = []; if(arrayVar) // Is the result of this condition true, or false? – Thiago Yoithi Nov 30 '17 at 16:57
  • @ThiagoYoithi in Javascript empty array [] is true, also empty object {}... because they are not values like 0, null, undefined etc... These are check for values... anyway good point to add it to my answer.... – Alireza Nov 30 '17 at 23:56
  • 2
    @Alireza, nice! Your answer will help a lot of people out there. I already memorized these falsy values, the only thing that I wasn't sure was about []. – Thiago Yoithi Dec 01 '17 at 20:01
  • Regarding the "check me please": This is correct because null and undefined are both "faulty" primitive types. They both represent "nothing" aka "void", so nothing != void is false – DerpyNerd Oct 15 '18 at 21:40
  • 20
    I get a "ReferenceError: elem is not defined" – ropo Nov 19 '18 at 10:05
  • 3
    @ropo, it's because you even didn't define the elem to check what it's , if it's your case, you need to check it with typeof(elem)==="string" which is mentioned already... – Alireza Nov 19 '18 at 12:09
  • 30
    Then the answer is misleading when it says `if(elem)` checks for undefined (while it returns not defined error), isn't it? – Fanky May 14 '19 at 14:34
  • Tested the last case it works for undefined and null: https://codesandbox.io/s/lingering-lake-4cdfh – Xitcod13 Jun 27 '19 at 18:46
  • i agree with franky, this answer looks like it would solve ops problem, but it does not have the same effect as the other answers (which is checking if a value exists) – fogx Aug 13 '19 at 10:49
  • This is wrong. `bar=undefined` is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. – oligofren Sep 24 '19 at 06:14
  • 1
    Give me a use case for checking if a variable is undefined and if is defined with an undefined value? Some of you are grasping at straws and attempting to look brilliant but if you are setting a value as undefined and checking for that value obviously it will return false or you need to change your code, smh.... this answer is correct!!!!! – almcaffee Nov 07 '19 at 17:25
  • 2
    Surprised my the number of upvotes. The answer is simply wrong. As mentioned in comments above, "if (elem) {}" does not check for undefined, it will throw an error if the variable is not defined. However, "if (window.elem) {}" will not throw an error if elem is undefined. – mhenry1384 Nov 21 '19 at 19:04
  • NOt correct. Doesn't catch completely undefined variables which is what the OP asked. – john ktejik Apr 26 '20 at 20:47
  • `(someUndefinedVariableName)` fails with `Uncaught ReferenceError: someUndefinedVariableName is not defined`, so I think this answer is wrong. – nacholibre Apr 29 '20 at 09:48
217

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 window.name 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.

Brian Kelley
  • 2,294
  • 1
  • 10
  • 5
  • 10
    This only checks if the variable was declared globally. If you are coding properly, then you are limiting your global vars. It will report false for local vars: (function() { var sdfsfs = 10; console.log( "sdfsfs" in window); })() ` – Eddie Monge Jr Jun 05 '13 at 23:00
  • 3
    This is the best f$#^%ing answer. I was at wit's end on this trying to figure out how to account for *exactly* this corner case. Brilliant. Had no idea you could do this. – temporary_user_name Jan 22 '14 at 03:05
  • 1
    Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
  • For Angular users: Unfortunately, it doesn't seem to be allowed in an ng-if statement. – qwertzguy Feb 10 '16 at 10:37
  • ...perfect blueprint for checks along scope. have you any performance indication, if "in window" or "(typeof variable === 'undefined' || variable === null)". Actually I am interested in a hard fact test and not in argumented potential rationale (which I could do myself: second clause has more operations -> worse performance) – Quicker Mar 11 '16 at 11:39
  • found one: http://andrew.hedges.name/experiments/in/. looks like plain (variable === 'undefined') is faster than if-in. I think I write the author of that site to add a test for (typeof variable === 'undefined' || variable === null) – Quicker Mar 11 '16 at 11:43
  • I don't think (variable === 'undefined') works. If you call a variable which is not declared, wouldn't it throw a ReferenceError? If there is a way to use this technique (property in window) for local scope, it would be great. – Hp93 Aug 24 '16 at 17:30
  • This is a great answer. Local scope does not work, of course, because the `in` is checking for an object property "in" an object, in this case `window`. "Global variables" are those variables who are properties of the window object. To use non-global variables in this way, the `window` in the `"myVariable" in window` statement would have to be replaced with an object, and the local variable would have to be a property of some such object. – Cannicide Oct 19 '19 at 16:58
  • `===` makes no sense here.. result of `typeof` is always string right? `== 'undefined'` is enough – l00k Nov 04 '19 at 11:25
  • @l00k yes, both work here, but it makes more sense to rely on strict comparisons wherever possible and just try to treat `==` as nonexistent, as it provides not much besides confusion and error-proneness – phil294 Jul 23 '20 at 16:34
  • @phil294 yeah I know that philosophy ;) but in my programmer history (more than 10 years) I still think - as far as you know what you are doing "==" is enough. – l00k Jul 24 '20 at 13:43
  • This doesn't work for `const` or `let` variables – asdf3.14159 Apr 05 '21 at 18:54
124

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) ...

Or:

(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.

David Tang
  • 86,742
  • 28
  • 159
  • 145
  • 21
    I'm shocked that you can override `undefined`. I don't even think that's worth mentioning in the answer. Probably the single worst acceptable variable name in all of Javascript. – Cory Danielson Apr 16 '13 at 06:53
  • 2
    This causes an exception and requires you to use `window.` before the variable if used in the global context...this is not the best way. – Alex W Sep 09 '13 at 14:42
  • 4
    Because of this overriding issue you should ALWAYS use `void(0)` instead of `undefined`. – Bartłomiej Zalewski Oct 23 '14 at 10:29
  • +1 since this answer points out that sometimes you may actually *want* to identify `false`, `0`, etc. as invalid values. – rinogo Jun 26 '18 at 23:41
94

Check if window.hasOwnProperty("varname")

An alternative to the plethora of typeof answers;

Global variables declared with a var varname = value; statement in the global scope

can be accessed as properties of the window object.

As such, the hasOwnProperty() method, which

returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)

can be used to determine whether

a var of "varname" has been declared globally i.e. is a property of the window.

// 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
] );

What's great about hasOwnProperty() is that in calling it, we don't use a variable that might as yet be undeclared - 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!

Notes

The above is true when using var to define a variable, as opposed to let which:

declares a block scope local variable, optionally initializing it to a value.

is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

At the top level of programs and functions, let, unlike var, does not create a property on the global object.

For completeness: const constants are, by definition, not actually variable (although their content can be); more relevantly:

Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.

The value of a constant cannot change through reassignment, and it can't be redeclared.

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

Since let variables or const constants are never properties of any object which has inherited the hasOwnProperty() method, it cannot be used to check for their existence.

Regarding the availability and use of hasOwnProperty():

Every object descended from Object inherits the hasOwnProperty() method. [...] unlike the in operator, this method does not check down the object's prototype chain.

Community
  • 1
  • 1
Fred Gandt
  • 3,691
  • 1
  • 29
  • 37
  • 2
    This an awesome alternative and should be on the top upvoted of this question. Please simplify the answer headline with a working example that returns `true` (e.g. `window.hasOwnProperty('console')` or `var hop = "p";window.hasOwnProperty('hop')`). – CPHPython Sep 14 '16 at 11:38
  • No need to define a function for explaining, people will understand it immediately and a short answer is faster to read. If you still want to leave the snippet, just leave two lines on it, the first defining the var and the second printing the result. – CPHPython Sep 14 '16 at 11:39
  • 3
    Finally something that does not throw an error because of accessing a member which does not exist … Something all the `typeof` answers simply overlook. – Zelphir Kaltstahl May 17 '17 at 08:17
  • 2
    This answer is outdated -- per standard ECMAScript you can define variables with `let` where these variables aren't available as properties of the `window` [or any other available] object. `hasOwnProperty` tests for presence of *properties*, not variables and thus cannot be used to detect variables defined by `let`. – amn Jun 15 '19 at 14:55
  • 1
    @amn The answer remains true regarding the use of `var` and is in that regard not outdated. I have however added a note outlining how the use of `let` and `const` differs from that of `var`. Thanks for your inspiration; together we rise :) – Fred Gandt Jun 15 '19 at 16:08
  • Fred, that's an honest effort, thanks. If I were you, I'd put the cherry on top of the cake by mentioning explicitly that variables defined by `let` and `const` (the latter not truly *variable*) are not accessible as properties of any object and therefore the `hasOwnProperty` usage shown in the answer does not apply to these, for obvious reasons. – amn Jun 16 '19 at 11:42
  • @amn It is precisely because it is "obvious" and because there is no implication that `let` (or `const`) variables can be accessed by `hasOwnProperty` that I will leave the answer as is (although I will make a tiny note indicating that I mention `const` only for *completeness* ). – Fred Gandt Jun 16 '19 at 13:44
  • 2
    @amn I have rewritten the answer (hopefully for the last time) to make more clear that `hasOwnProperty` can only be used in the prescribed manner to check for the existence of `var` variables. It reads okay to me. – Fred Gandt Jun 17 '19 at 18:31
  • Unfortunately not working under IE 11. `hasOwnProperty('indexedDB')` always return `false`, for example even though `indexedDB` does exist – yiwen Aug 29 '19 at 21:03
  • @yiwen I see that `window.hasOwnProperty("indexedDB")` returns `false` on IE11 while `window.indexedDB` returns the object. On Chrome, the same code returns `true`. IE11 however returns expected results for other checks (e.g. `var foo="foo"; window.hasOwnProperty("foo");` returns `true`), so to say it's "not working" is not quite true. IE11 is clearly just being as temperamental as its ancestors. – Fred Gandt Aug 30 '19 at 21:42
  • A statement like "something is not working" is either true or false. As long as it fails in one case it qualifies as not working – yiwen Aug 31 '19 at 23:37
  • Don't get me wrong, I like your method and I think it is very smart way to go. But before we can get rid of IE11 support, I, unfortunately, cannot use this method – yiwen Sep 01 '19 at 00:44
  • This should be accepted answer. The `typeof` is useless if the variable has not been declared yet. – shrimpwagon Apr 23 '21 at 17:01
71

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) {
    console.log(isset(x));
    console.log(isset(y));
};

test(a);

// OUTPUT :
// ------------
// TRUE
// FALSE

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.

Community
  • 1
  • 1
John Slegers
  • 38,420
  • 17
  • 182
  • 152
47

Short way to test a variable is not declared (not undefined) is

if (typeof variable === "undefined") {
  ...
}

I found it useful for detecting script running outside a browser (not having declared window variable).

user2878850
  • 1,938
  • 1
  • 14
  • 17
  • is this the "canonical way" that is portable? – Jason Jul 18 '19 at 14:44
  • 3
    This is wrong. `window.bar=undefined` is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. If you did `this.hasOwnProperty('bar')` it might have worked. – oligofren Sep 24 '19 at 06:15
  • this code doesn't work and you can verify this by using any browser console – ha9u63ar Feb 13 '20 at 08:59
  • 1
    Consider `const x = 0; (() => console.log(x, this.hasOwnProperty('x')))();`. Variable `x` is defined but false is returned... – user2878850 Mar 05 '20 at 22:55
41

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 : '';
RajeshKdev
  • 6,029
  • 6
  • 53
  • 76
  • the answer as it is flat out wrong. typeof variable always returns a string, thus is never false. e.g. if `typeof(booooo)` is `"undefined"` then `typeof(typeof boooooo)` is `"string"` and `typeof boooooo && true` is always `true`. @John-Slegers' answer is about as abbreviated as you can get with typeof. – mpag May 05 '17 at 20:05
  • **Its absolutely correct answer**. [**Here is an working Fiddle**](https://jsfiddle.net/o5mzrsfc/1/). And i don't know which scenario you are talking about. The questions is about checking variable existence. – RajeshKdev May 06 '17 at 05:11
  • @mpag Don't Say Flat wrong. **Prove It**. Finding a mistake is real easy, instead you can provide Good answers here!!!. If the answer is flat wrong **28** programmers wouldn't have up-voted without checking my answer. Since there are many reputed answers here they could have up-voted that, not this. – RajeshKdev May 06 '17 at 05:20
  • Actually the second piece of code, is not to check same as above condition. I thought people would understand by this line `If you wanted to check variable shouldn't be undefined or null.`, By this comment, its clearly stating, its not to perform the variable declaration check. that's to check variable value. – RajeshKdev May 09 '17 at 05:56
  • Removed the `typeof`, which was misleading/gives the error. and updated this comment `When the variable is declared, and if you want to check the value, this is even Simple`, I hope this gives the clear answer. – RajeshKdev May 09 '17 at 05:58
  • Thanks for making me correct my answer, Now, clearly we have condition to check JavaScript check if variable exists (is **defined/initialized**), And this answer is not flat out wrong anymore. ;) – RajeshKdev May 09 '17 at 06:03
  • :) quite a bit improved. I'm not quite sure what you mean by "it would perform both checks together" as it's not checking if a variable is declared. It would be assigning a "null" string value if the first variable is declared but not defined. – mpag May 09 '17 at 17:40
  • 1
    your 2nd check will fail with 0 value – Fareed Alnamrouti May 30 '17 at 08:30
  • This is wrong. `bar=undefined` is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. – oligofren Sep 24 '19 at 06:12
35

It depends if you just care that the variable has been defined or if you want it to have a meaningful value.

Checking if the type is undefined will check if the variable has been defined yet.

=== null or !== null will only check if the value of the variable is exactly null.

== null or != null will check if the value is undefined or null.

if(value) will check if the variable is undefined, null, 0, or an empty string.

Alan Geleynse
  • 23,597
  • 5
  • 43
  • 54
13

Try-catch

If variable was not defined at all, you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)

try{
  notDefinedVariable;
} catch(e) {
  console.log('detected: variable not exists');
}

console.log('but the code is still executed');

notDefinedVariable; // without try-catch wrapper code stops here

console.log('code execution stops. You will NOT see this message on console');

BONUS: (referring to other answers) Why === is more clear than == (source)

if( a == b )

Enter image description here

if( a === b )

Enter image description here

Community
  • 1
  • 1
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
12

The highest answer is correct, use typeof.

However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (@skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.

The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...

shadowstorm
  • 231
  • 3
  • 7
  • 1
    The point is moot, because if varName is undefined then `varName !== undefined` will just cause a ReferenceError. The mutability of `undefined` won't matter. – Wutaz Mar 27 '14 at 23:53
  • Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
  • 1
    In newer Javascript versions `undefined` is an read only property. However to be bulletproof you can use `typeof mvVar === typeof void 0`. `void 0` returns `undefined` always. – kwarnke Sep 20 '17 at 10:32
11
if (typeof console != "undefined") {    
   ...
}

Or better

if ((typeof console == "object") && (typeof console.profile == "function")) {    
   console.profile(f.constructor);    
}

Works in all browsers

boslior
  • 119
  • 1
  • 2
  • 3
    Why the latter is better in your opinion? – skalee Feb 17 '13 at 03:32
  • 3
    @skalee I agree the latter is better. This for the simple reason that you check if the types are the ones you want before using them. – Broxzier Jul 10 '13 at 14:31
  • Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
10

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;
    }
    alert(message); 
}

..could be reduced to:

if (data && !data.url) {
  var message = data.error || data.message || 'Error receiving response';
  alert(message)
} 
Community
  • 1
  • 1
de3
  • 1,678
  • 5
  • 20
  • 35
  • This is not what the OP asked. If data.url is equal to `''` your solution would consider it undefined, when it is in fact defined as containing an empty string. – Demonblack Jan 14 '18 at 23:01
  • 1
    I agree is not what has been asked, and you are right: the empty string '' would be considered undefined. But I posted this because I thought it could be useful on the debate that has been created among different answers. And in the example, as well as in many other cases, you just want to print a string if there is actually content, so it's ok to take advantage of the fact the javascript considers falsy both empty string and undefined – de3 Jan 19 '18 at 16:18
9

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
}
Razan Paul
  • 12,148
  • 3
  • 64
  • 59
8

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;
Community
  • 1
  • 1
Zv_oDD
  • 1,615
  • 17
  • 25
8

I use two different ways depending on the object.

if( !variable ){
  // variable is either
  // 1. '';
  // 2. 0;
  // 3. undefined;
  // 4. null;
  // 5. false;
}

Sometimes I do not want to evaluate an empty string as falsey, so then I use this case

function invalid( item ){
  return (item === undefined || item === null);
}

if( invalid( variable )){
  // only here if null or undefined;
}

If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.

SoEzPz
  • 11,914
  • 8
  • 56
  • 58
8

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); 
alert(_null); 
alert(_undefined == _null);
alert(_undefined === _null);

Liam
  • 22,818
  • 25
  • 93
  • 157
Jith
  • 1,629
  • 2
  • 15
  • 22
  • 1
    Would be helpful to show inline the output of each alert. – demisx Jan 02 '15 at 06:17
  • @demisx Agreed, but instead of suggesting the edit, why not just make it? The option is there for a reason. Some may consider it rude; I consider it efficient - so edited the answer myself (pending review). – Fred Gandt Jun 12 '15 at 12:32
  • 1
    @Fred - I looked at the edit history and can guess why your edits were rejected... rather than just adding lines to show what the output would be, as demisx suggested, you significantly changed what Jith had posted. – Stephen P Jul 02 '15 at 21:15
7

you can use the typeof operator.

For example,

var dataSet;

alert("Variable dataSet is : " + typeof dataSet);

Above code snippet will return the output like

variable dataSet is : undefined.

Liam
  • 22,818
  • 25
  • 93
  • 157
Ravindra Miyani
  • 196
  • 4
  • 14
  • 1
    Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
7

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 {
  someVar;
  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");
}
Ferran Maylinch
  • 9,556
  • 13
  • 70
  • 89
  • What do you mean by "extract the code to a function"? – Melab Jan 26 '20 at 00:31
  • @Melab Ideally you could have `function isDefined(x){...}` and then call `isDefined(myVar)`. But there is no way to safely pass a potentially undefined variable to `isDefined` because before the variable can be passed to the function, it must be evaluated, and if it doesn't already exist, then at that point it will throw (outside of the `try/catch` block, which is *in* the function). You have to evaluate the variable directly inside a `try/catch` block, so you cannot wrap the test in a function. – BallpointBen Jan 25 '21 at 18:57
6

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.

skalee
  • 10,976
  • 6
  • 47
  • 54
  • Heads-up: your answer has been migrated here from http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – Shog9 Jul 25 '14 at 16:33
  • 2
    False. the latter throws an exception in my console. – john ktejik Oct 11 '14 at 01:25
6

My preference is typeof(elem) != 'undefined' && elem != null.

However you choose, consider putting the check in a function like so

function existy (x) {
    return typeof (x) != 'undefined' && x != null;
}

If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;

Where you know the variable is declared but may not be existy, you could use

existy(elem) && doSomething(elem);

The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:

var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;

After each property use (...' || {}').nextProp so that a missing property won't throw an error.

Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)

curtwphillips
  • 4,462
  • 1
  • 17
  • 18
  • If you put it in a function, it’s redundant. `typeof (x) != 'undefined' && x != null` is equivalent to `x != null` when `x` is declared. – Ry- Jun 01 '19 at 04:12
5
if (variable === undefined) {}

works just fine, and only checks for undefined.

John Lord
  • 1,261
  • 6
  • 21
4

Attention :: people who don't understand the difference between a proposition let, a constant const and a variable var should refrain themselves from commenting.

These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.

Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?

Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?

We do it by using the most powerful JasvaScript operator, the in operator.:

"[variable||property]" in [context||root] 
>> true||false

In times of AJAX peaking popularity I've written a method (later named) isNS() which is capable of determining if the namespace exists including deep tests for property names such as "Book1.chapter22.paragraph37" and a lot more.

But since it has been previously published and because of its great importance it deserves to be published in a separate thread I will not post it here but will provide keywords (javascript + isNS ) which will help you locate the source code, backed with all the necessary explanations.

Bekim Bacaj
  • 4,530
  • 1
  • 19
  • 25
4

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"
jpsimons
  • 24,016
  • 3
  • 31
  • 45
4

You could use a try...catch block like the following:

var status = 'Variable exists'

try {
  myVar
} catch (ReferenceError) {
  status = 'Variable does not exist'
}

console.log(status)

A disadvantage is you cannot put it in a function as it would throw a ReferenceError

function variableExists(x) {
  var status = true
  try {
    x
  } catch (ReferenceError) {
    status = false
  }
  
  return status
}

console.log(variableExists(x))

Edit:

If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:

function globalVariableExists(variable) {
  if (window[variable] != undefined) {
    return true
  }
  
  return false
}

var x = undefined

console.log(globalVariableExists("x"))

console.log(globalVariableExists("y"))

var z = 123

console.log(globalVariableExists("z"))

Edit 2:

If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:

function variableExists(variable, thisObj) {
  if (thisObj[variable] !== undefined) {
    return true
  }
  
  return false
}

class someClass {
  constructor(name) { 
    this.x = 99
    this.y = 99
    this.z = 99
    this.v = 99
    
    console.log(variableExists(name, this))
  }
}

new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
GalaxyCat105
  • 2,105
  • 4
  • 12
  • 26
2

I prefer this method for it's accuracy and succinctness:

var x
if (x === void 0) {
  console.log(`x is undefined`)
} else {
  console.log(`x is defined`)
}

As has been mentioned in other comments and answers, undefined isn't guaranteed to be undefined. Because it's not a keyword, it can be redefined as a variable in scopes other than the global scope. Here's little example that demonstrates this nuance:

var undefined = 'bar'
console.log(`In the global scope: ${undefined}`)

function foo() {
  var undefined = 'defined'
  var x
  if (x === undefined) {
    console.log(`x === undefined`)
  } else {
    console.log(`x !== undefined`)
  }
  if (x === void 0) {
    console.log(`x === void 0`)
  } else {
    console.log(`x !== void 0`)
  }
}

foo()

See void for compatibility (supported in IE5!?!! Wow!).

Trevor
  • 11,966
  • 11
  • 74
  • 94
1

I'm surprised this wasn't mentioned yet...

here are a couple of additional variations using this['var_name']

the benefit of using this method that it can be used before a variable is defined.

if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part

// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
Daniel
  • 24,073
  • 15
  • 74
  • 123
  • This is wrong. `window.bar=undefined` is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. If you did `this.hasOwnProperty('bar')` it might have worked. – oligofren Sep 24 '19 at 06:14
0

In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since react-scripts@2.0.3 (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...

In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....

This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.

So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.

This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.

But, for ReactJS, you can use eval(). If you have an undeclared variable like...

if(undeclaredvar) {...}

You can simply rewrite this part as...

if(eval('typeof undeclaredvar !== "undefined"')) {...}

For instance...

if(eval("false")) {
  console.log("NO!");
}
if(eval("true")) {
  console.log("YEAH!");
}

For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.

HoldOffHunger
  • 10,963
  • 6
  • 53
  • 100
-1

You can also use !! before a variable to check if it's defined. E.g.

let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");

Output:

1.
Both are NOT defined
2. 
Both are defined
daCoda
  • 2,443
  • 4
  • 24
  • 32
  • is this a node construct and if so which version ... I was searching for exactly this and can't seem to find it ... JavaScript :shakesfirst: – DanCat Oct 30 '20 at 20:25
  • This is quite wrong, this checks only whether the variable is truthy, not defined. `!!0` is false even though `0` is defined. – jcaron Jan 29 '21 at 14:00
-2

This was the best solution from me:

var $;
  if($.css == undefined){console.log('JQ IS NOT PRESENT')}else{console.log('JQ VERSION ' + jQuery.fn.jquery + ' IS PRESENT')}
  • your code is functional, if not basically identical to my answer. You would probably get upvotes if you edit it and format your answer so it's multi-line. currently it's scrolled off of the screen, and has no comments or spacing. – John Lord May 04 '21 at 20:56