Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

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');
        alert('1 Undefined');
    alert('1 okay');

In JavaScript 1.1 you can use typeof:

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

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');
    alert('3 okay');

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

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

©2018 Martin Webb