Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q778 How can I test to see if a variable has been assigned a value/declared?

You are here: irt.org | FAQ | JavaScript | Misc | Q778 [ previous next ]

With difficulty.

In JavaScript 1.3 you can use the === operator to check for undefined:

<SCRIPT LANGUAGE="JavaScript1.3"><!--
var undefined;

if (typeof variable1Name == 'undefined') {
    if (variable1Name === undefined)
        alert('1 Null');
    else
        alert('1 Undefined');
}
else
    alert('1 okay');
//--></SCRIPT>

In JavaScript 1.1 you can use typeof:

<SCRIPT LANGUAGE="JavaScript1.1"><!--
if (typeof variable2Name == 'undefined')
    alert('2 Undefined');
else
    alert('2 okay');
//--></SCRIPT>

Although this also triggers undefined, if the variable is defined but has no value:

<SCRIPT LANGUAGE="JavaScript1.1"><!--
var variable3Name;
if (typeof variable3Name == 'undefined')
    alert('3 Undefined');
else
    alert('3 okay');
//--></SCRIPT>

In earlier versions of JavaScript you can only test for null:

<SCRIPT LANGUAGE="JavaScript"><!--
if (variable4Name == null)
    alert('4 Null');
else
    alert('4 okay');
//--></SCRIPT>

©2018 Martin Webb