A Friday Freebie! (was: RE: [thelist] Flash version of Heirmenus)

Scott Dexter sgd at ti3.com
Fri Jun 1 15:10:51 CDT 2001


The title of this thread makes me giggle. Am I the only one who is
transfixing Heirmenus to be some lost Roman figure?

Heirmenus, who was known throughout land and time for his great speed and
incredibly organized battle strategies, battled alongside Linus against the
tyranny of Jakob. Er something...

That, my friends, is about as off topic as you can get around here, and for
such tomfoolery, a tip (one on a Friday even, when was the last time *that*
happened?)

<tip type="javascript">
(that should mess up a couple html-enabled mail readers, heh)

Don't forget about the scoping of your variables. You can get into trouble
real quick. Let's say I have a function that calls a second function
(slightly pseudocoded):

<script language="javascript">
function AddEmUp(thing1, thing2)
{
	for (i=0;i<=thing1.value.length;i++) {
		total = AddDigit(thing1.value) + AddDigit(thing2.value);
	}
	Return total;
}

function AddDigit(vstring)
{
	for (i=0;i<=vstring.length;i++){
		minitotal = vstring.value + 1;
	}
	return minitotal
}
</script>

There's a potential problem here. The variable i in the second function is
*THE SAME* variable i as the first function. Because we haven't defined the
variable, the scoping rules in javascript (as other procedural languages)
dictate that the variable i in the first function is used. That means i gets
changed a whole lot, and unexpected results happen (think about the case
where thing2's length is longer than thing1's --all of a sudden you're
exiting the loop a lot earlier than you'd think)

So, follow one good coding conventions you chose to forget cause it's lazy:
Declare your variables!

<script language="javascript">
function AddEmUp(thing1, thing2)
{
var i;
	for (i=0;i<=thing1.value.length;i++) {
		total = AddDigit(thing1.value) + AddDigit(thing2.value);
	}
	Return total;
}

function AddDigit(vstring)
{
var i;
	for (i=0;i<=vstring.length;i++){
		minitotal = vstring.value + 1;
	}
	return minitotal
}
</script>


There. No scoping problems ... with 'i' anyways... ;)
</tip>

sgd




More information about the thelist mailing list