JavaScript check if variable exists (is defined/initialized)

ID : 407

viewed : 158

Tags : javascriptvariablesinitializationundefinedjavascript





Top 5 Answer for JavaScript check if variable exists (is defined/initialized)

vote vote

92

You want the typeof operator. Specifically:

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

89

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?

vote vote

70

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

vote vote

69

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.

vote vote

50

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.

Top 3 video Explaining JavaScript check if variable exists (is defined/initialized)







Related QUESTION?