473,386 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Reference to possibly undefined variable

If you want your code to be bulletproof, do you have to explicitly check
for the existence of any possibly-undefined variable?

Example: window.outerHeight is defined by some browsers, but not others.
It would therefore seem prudent, before using this variable, to do
something like:
if (typeof (window.outerHeight) != "undefined") { do stuff that
refers to this variable }
else { work around the fact that the variable isn't defined }

1. Is this really necessary? Bad things seem to happen if even
relatively harmless use is made of an undefined variable, such as
document.write ("Height is " + window.outerHeight)
By 'bad things" I mean that the whole script comes to a halt.

2. Aside from something like:
(typeof (window.outerHeight) != "undefined") ? x = window.outerHeight
: x = "undefined"
is there a more concise way of doing this?

3. Are the consequences of using an undefined variable actually
documented in any authoritative place?

Chris Beall

Jul 23 '05 #1
4 4118
Chris Beall wrote:
If you want your code to be bulletproof, do you have to explicitly check
for the existence of any possibly-undefined variable?
Yes, how else?

Example: window.outerHeight is defined by some browsers, but not others.
It would therefore seem prudent, before using this variable, to do
something like:
if (typeof (window.outerHeight) != "undefined") { do stuff that refers
to this variable }
else { work around the fact that the variable isn't defined }

1. Is this really necessary? Bad things seem to happen if even
relatively harmless use is made of an undefined variable, such as
document.write ("Height is " + window.outerHeight)
By 'bad things" I mean that the whole script comes to a halt.
You must determine what, for the purpose of your script, are
"bad things". Usually a graceful exit is required such that the
user does not notice any lack of functionality or failure to
successfully complete an action.

Where a function can't be performed for some reason, either an
alternative should be offered (e.g. by a trip to the server to
accomplish what might otherwise have happened in the page) or
the functionality is not exposed at all.

2. Aside from something like:
(typeof (window.outerHeight) != "undefined") ? x = window.outerHeight
: x = "undefined"
is there a more concise way of doing this?
var x = window.outerHeight || 'undefined';

Which will fail if "window" is not defined, but I think we're
safe there. But of course you must now test x to see what
happened, so your next line will likely be:
if (x) {
// do something with x
}

So you may as well do:

var x;
if ( typeof window.outerHeight != 'undefined'
&& x = window.outerHeight){
// do something with x
}

Or, since window.outerHeight should be a number:

var x;
if ( typeof window.outerHeight == 'number'
&& x = window.outerHeight){
// do something with x
}

3. Are the consequences of using an undefined variable actually
documented in any authoritative place?


Yes, in the official ECMA documentation for JavaScript. Links to
various versions and formats are here:

<URL:http://www.mozilla.org/js/language/>

There are 129 references to "undefined", including how
'undefined' is treated in a variety of contexts. A useful
discussion of the topic you have raised is here:

<URL:http://cleancode.sourceforge.net/wwwdoc/codingRules/vr4.html>

In short:

A reference to an *undeclared* variable will cause your script
to error and terminate. A reference to an *undefined* variable
will return 'undefined'. What your script does with that is up
to you, but it may cause a script error on some subsequent step.

For example, suppose you try:

if(n) {...}

when 'n' is undeclared, your script will go belly-up. However,
if it has been declared but has not yet be defined, n will
return 'undefined' and the test will return 'false';

But, even though an undeclared 'n' is OK at this point, it may
cause a script error later - e.g.:

var n; // n declared but undefined;
var x = document.forms[n]; // x is undefined too
var y = document.forms[n].elements // script error...

The above will run until it attempts to evaluate:

...forms[n].elements

at which point it will error and terminate. :-(
--
Rob
Jul 23 '05 #2
RobG wrote:

Sorry, did a spell check and clicked post before I was ready!

[...]
is there a more concise way of doing this?
var x = window.outerHeight || 'undefined';


Which presumes window.outerHeight is != 0, which it should not
be. Using OR sets x to the string 'undefined', so a subsequent
test of:

if (x != 'undefined')

can be used. Alternatively, you can use:

var x = window.outerHeight;
if ( x != undefined )

Whatever you think is more maintainable.

[...] Or, since window.outerHeight should be a number:

var x;
if ( typeof window.outerHeight == 'number'
&& x = window.outerHeight){
// do something with x
}


Which leads back to the cleanest, most easily maintained version
which is:

if ( window.outerHeight != undefined ){
var x = window.outerHeight;
// do more stuff maybe
} else {
// get x some other way
// do stuff differently maybe
}

Which avoids a slower 'typeof' test (but the slowness may be
trivial).

Note that some numeric values also return their units, such as
using getComputedStyle to return an element's height, so even
though they might appear to be numeric, they return something
like "358px" or "55em", etc. so testing for undefined is
probably the most robust general test.
--
Rob
Jul 23 '05 #3
RobG wrote:
Chris Beall wrote:
If you want your code to be bulletproof, do you have to explicitly
check for the existence of any possibly-undefined variable? (snip) 2. Aside from something like:
(typeof (window.outerHeight) != "undefined") ? x =
window.outerHeight : x = "undefined"
is there a more concise way of doing this?

var x = window.outerHeight || 'undefined';

Which will fail if "window" is not defined, but I think we're
safe there. But of course you must now test x to see what
happened, so your next line will likely be:

(snip)

But I did say bulletproof.... :-)
3. Are the consequences of using an undefined variable actually
documented in any authoritative place?

Yes, in the official ECMA documentation for JavaScript. Links to
various versions and formats are here:

<URL:http://www.mozilla.org/js/language/>

(snip)

Aha! That's what I didn't find with Google.
In short:

A reference to an *undeclared* variable will cause your script
to error and terminate. A reference to an *undefined* variable
will return 'undefined'. What your script does with that is up
to you, but it may cause a script error on some subsequent step.

For example, suppose you try:

if(n) {...}

when 'n' is undeclared, your script will go belly-up. (snip)

Precisely what I want to avoid. It appears that 'typeof' is the only
safe thing to use, as it will return 'undefined' for either an
undeclared or undefined variable.

But, even though an undeclared 'n' is OK at this point, it may
cause a script error later

(snip)

Understood. That's why I want to identify the situation up front and
adjust for it on the spot.

Net: typeof is the only bulletproof way. Using 'if' is also less obtuse
than using a logical OR. The performance impact is small (and not
relevant in my case).

Many thanks, Rob
Chris Beall


Jul 23 '05 #4
Chris Beall wrote:
[...]

Net: typeof is the only bulletproof way. Using 'if' is also less obtuse
than using a logical OR. The performance impact is small (and not
relevant in my case).


Not exactly, you don't have to test for 'typeof' explicitly.
Read this thread, in particular Mike Winter's comments.
news://inetbws1.citec.qld.gov.au:119/7wCUd.525795$6l.338062@pd7tw2no

or
<URL:http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/37e9b705ece03d33/ac3ea134c9e85063?q=Can+I+check+if+an+object+exists %3F&_done=%2Fgroup%2Fcomp.lang.javascript%2Fsearch %3Fq%3DCan+I+check+if+an+object+exists%3F%26start% 3D0%26scoring%3Dd%26&_doneTitle=Back+to+Search&&d# ac3ea134c9e85063>

--
Rob
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

36
by: Riccardo Rossi | last post by:
Hi all! How does Python pass arguments to a function? By value or by reference? Thanks, Riccardo Rossi.
110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
6
by: ged | last post by:
Hi, i am a oo (c#) programmer, and have not used javascript for a while and i cant work out how javascript manages its references. Object References work for simple stuff, but once i have an...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
7
by: Plissken.s | last post by:
Is it possible to const_cast a reference? If not , how can I remove to 'const' from a reference? void aMethod2(A& a) { } void aMethod1(const A& a) {
10
by: ma740988 | last post by:
I'm perusing source that quite frankly looks like a disaster in the making. This is a case though where return by reference gets muddled with my understand based on readings. struct bar {...
27
by: David W | last post by:
I'm almost tearing my hair out. A colleague claimed that a null reference can exist, like this: void f( int& p ) { printf( "%d\n", p ); } int main (int argc, char *argv) {
7
by: Zhang Weiwu | last post by:
Dear all How does javascript realiablily tell if a variable is a reference to an HTML Element "<select>", without causing browser to pop up error message? if (variable.constructor ==...
11
by: ravi | last post by:
Can anybody out there tell me whether it i possible to return a reference from a function in C++ I am using Turbo C++
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.