Whether a variable is undefined

Asked
Viewd431099

185

How do I find if a variable is undefined?

I currently have:

var page_name = $("#pageToEdit :selected").text();
var table_name = $("#pageToEdit :selected").val();
var optionResult = $("#pageToEditOptions :selected").val();

var string = "?z=z";
if ( page_name != 'undefined' ) { string += "&page_name=" + page_name; }
if ( table_name != 'undefined' ) { string += "&table_name=" + table_name; }
if ( optionResult != 'undefined' ) { string += "&optionResult=" + optionResult; }
431099
  • undefined is a property of javascript so doesn’t need to be in quotes. You’re checking to see if the values are actually the string ‘undefined’. http://www.w3schools.com/jsref/jsref_undefined.asp

    daddywoodland28 сентября 2009, 07:44

5 ответов

3
function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

312

jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:

if(page_name != '')

For other variables that don't come from something like jQuery.val() you would do this though:

if(typeof page_name != 'undefined')

You just have to use the typeof operator.

  • Yeah. You’re right about the undefined var part.

    ScottyUCSD28 сентября 2009, 15:05
  • if(undefinedVar) will throw an error, but if(someObj.undefinedProperty) will not. In the latter case, you can also skip typeof and use === undefined (or !==), without quotes.

    eyelidlessness28 сентября 2009, 08:56
  • И я поставил вам +1 за правильное указание на то, что методы jQuery не возвращают undefined.

    eyelidlessness28 сентября 2009, 08:56
122

if (var === undefined)

а точнее

if (typeof var === 'undefined')

Обратите внимание, что используется ===

-7

You can just check the variable directly. If not defined it will return a falsy value.

var string = "?z=z";
if (page_name) { string += "&page_name=" + page_name; }
if (table_name) { string += "&table_name=" + table_name; }
if (optionResult) { string += "&optionResult=" + optionResult; }
2

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }