tags:

views:

879

answers:

5

Could anyone please tell me how to 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; }
A: 

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; }
Rich Seller
+2  A: 

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.

ScottyUCSD
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.
eyelidlessness
And I gave you +1 for correctly pointing out that jQuery's methods won't return undefined.
eyelidlessness
Yeah. You're right about the undefined var part.
ScottyUCSD
A: 

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; }
micmcg
A: 

Check this question: http://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript

Natrium
So why not now vote to close as dupe instead of posting a non-answer?
random
A: 
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 no string concatenation)

DBJDBJ