Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether a variable is undefined [duplicate]

Tags:

jquery

People also ask

How do you know if a variable is undefined?

So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .

Why a variable is undefined?

An undefined variable is a variable used in a program that was not previously declared in the source code. In most programming languages, this results in an error.

How do you know if not equal to undefined?

If you want to check if x is strictly equal to undefined regardless of whether is has been declared or not, you should use typeof x === 'undefined' .

How check variable is undefined or not in JavaScript?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .


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.


if (myVariable === undefined)

or more precisely

if (typeof myVariable === 'undefined')

Note the === is used


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


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; }