[thelist] JavaScript Functions and correctly returning values

Jackson Yee jyee at vt.edu
Thu Aug 15 17:17:03 CDT 2002


----- Original Message -----
From: "Tom Dell'Aringa" <pixelmech at yahoo.com>
To: <thelist at lists.evolt.org>
Sent: Thursday, August 15, 2002 16:07
Subject: [thelist] JavaScript Functions and correctly returning values

> I'm just full of stuff today.. I read somewhere that you should
> *always* return a value from a function, even if its return false or
> null. So question 1 is, is that truly the case? I believe the author
> was speaking of "good programming habits" and the like.

In other programming languages such as C++ or Java, you would declare the
function void to save some extra processing done by having to return a value
(one extra MOV instruction for any old assembly programmers out there).  I'm
not sure about the efficiency of doing this in JavaScript though, as
JavaScript uses the keyword void as an valueless operator rather than as a
simple function return specification.

Personally, I don't really see any use for it, as I follow the philosophy that
if someone's stupid enough to say

var Foo = bar();

when bar() has been clearly documented as having no useful return value, then
that programmer deserves whatever comes to him or her.  It just takes up extra
room in your code and confuses people as to why the "return false" statement
is there in the first place.

Then again, I'm sure that the author had his own valid reasons for suggesting
the return value.

> Secondly, note the following function:
>
> function Collection() {
>   this.length = 0;
>   this.add = add;
>   return this;
> }
>
> This is a constructor function. I've never seen "return this" at the
> end of a constructor. It's certainly not required, but does this go
> along with my first question? I'm assuming that saying return this
> will in fact return the value of all the objects properties.
>
> Of course, the function would have done this anyway. Is using return
> adding any speed or effectiveness to the function, or is it just a
> "best practice"?

In JavaScript < 2.0, using "return this;" was recommended if you had added
anything onto the object according to

http://wsabstract.com/javatutors/serror2.shtml

However, in JavaScript 2.0, it is stated that

"A constructor should not return a value with a return statement; the newly
created object is returned automatically. A constructor’s return type must be
omitted."

according to

http://www.mozilla.org/js/language/js20/core/classes.html

"Best practices" are almost always a matter of opinion, so choose what works
best for you, and go with it.  I'm personally a very lazy coder, so if there's
something that I don't need to add, then I usually don't do it.  ;-)

Regards,
Jackson Yee
jyee at vt.edu
http://www.jacksonyee.com/




More information about the thelist mailing list