Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Misc | Q778 [ previous next ]

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

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.