[ANN] Updated Javascript Best Practices document

R

Randy Webb

(e-mail address removed) said the following on 6/6/2006 2:01 PM:
Matt Kruse wrote:



I would think the best practice would be "only use bracket notation
when dot notation will not work."

Think about what you are saying.

Dot Notation is a shortcut for Bracket Notation.

Use the shortcut instead of the brackets until the shortcut doesn't work
and then use the brackets.

Do you also think it would be a good idea to use a shortcut in IE until
it doesn't work elsewhere?

<div id="myDiv"></div>

myDiv.innerHTML = "something new";

"works" (loosely worded) in IE. So, do you use the shortcut until it
doesn't work or do you just use a reliable fool proof way all the time
and not worry about it?

If you want fool proof and reliability, you use Brackets. But as has
been pointed out - many times already - there is no blanket 100% answer
to that question. It has a lot to do with personal preference.
 
P

petermichaux

Randy said:
(e-mail address removed) said the following on 6/6/2006 2:01 PM:

Think about what you are saying.

Dot Notation is a shortcut for Bracket Notation.

Use the shortcut instead of the brackets until the shortcut doesn't work
and then use the brackets.

Yes. You can build a house and break up a foundation with a 5 lb.
sledge hammer but you don't. You use a 16 oz. hammer to build a house.

Do you also think it would be a good idea to use a shortcut in IE until
it doesn't work elsewhere?

<div id="myDiv"></div>

myDiv.innerHTML = "something new";

"works" (loosely worded) in IE.

If your target includes browsers where this doesn't work then this is a
situation to use brackets.

So, do you use the shortcut until it
doesn't work or do you just use a reliable fool proof way all the time
and not worry about it?

You could use brackets all the time but I imagine few people do. I
understand your point about not having to worry if you use brackets but
I doubt I'll stop using dot notation. I imagine you will continue using
a dot or two in the future too.

If you want fool proof and reliability, you use Brackets. But as has
been pointed out - many times already - there is no blanket 100% answer
to that question. It has a lot to do with personal preference.

Maybe that should be mentioned in the best practices.

Peter
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Tue, 6 Jun 2006 11:01:14 remote, seen in
news:comp.lang.javascript, (e-mail address removed) posted :
I would think the best practice would be "only use bracket notation
when dot notation will not work."


Since dot notation is more compact, that is in principle good advice
(unless bracket notation is useful to denote references to names
specific to the page rather than general to the model).

But, for WWW use, "will not work" needs to be interpreted as "does not
work with at least one significant user agent out of the many possible";
and that's not *readily* tested for, even by a professional with many
browsers to hand.

Therefore your concisely-expressed principle needs, for practical use,
to be presented in a more explicit fashion.



ASIDE :
To copy an ordinary Date Object,
D1 = new Date(+D0)
or D2 = new Date(D0.valueOf())
D1 looks better; but in IE4 D2 seems faster (I see a /post hoc/
explanation). Do other browsers act similarly?

Both are much better than
D3 = new Date(D0)
 
B

Bart Van der Donck

Matt said:
http://www.javascripttoolbox.com/bestpractices/new.php

I've updated my Best Practices document to include more content and more
supporting arguments for the recommendations. Also, I've added #anchors to
each recommendation so linking to a specific recommendation is possible from
posts here, etc.

Your web site is a very nice initiative.

Why not join all useful javascript documents from various resources
into one general FAQ, "the" FAQ, so to say ? It should then cover as
much topics/tricks as possible. A search on this ng would certainly
result in further material for that general FAQ + the other sites like
jibbering.com etc.

And then a periodical automated post to Usenet (a FAQ a day or so) from
db. It's quite simple to make such a thing. And it's a great way to
keep the docs up-to-date.

There are other code newsgroups that work this way. In my opinion it's
a great system, but the noses must point into the same direction, of
course :)
 
M

Matt Kruse

Lasse said:
How do you justify using object["property"] as a best practice?
My personal justification is that it points out when something is
not a standard DOM property, i.e., when the name of the property
depends on something dynamic, including the document it is being used
with.

Lasse, I've added text to the document which describes this approach as the
recommended convention, since like I said before it is the rule I generally
follow also but never really thought about :)

The updated doc is now at:
http://www.javascripttoolbox.com/bestpractices/

And contains this text:

The recommendation for using square bracket notation is to always use it
when it is required (obviously). Using it when not strictly required is a
matter of personal preference and convention. One good rule of thumb is to
use dot notation to access standard properties of objects, and square
bracket notation to access properties which are defined as objects in the
page. So, while document["getElementById"]() is perfectly vaid using square
bracket notation, document.getElementById() is the preferred syntax because
getElementById is a standard property of the document object as defined in
the DOM specifications. Mixing the use of dot and square bracket notation
makes it clear which properties are standard and which are names defined by
the content:
document.forms["myformname"].elements["myinput"].value
Here, the forms property is a standard property of document, while the form
name myformname is defined by the page content. Likewise, the elements
property and value property are both defined by the specs, but then myinput
name is defined in the page. This syntax is very clear and easy to
understand and is a recommended convention to follow, but not a strict rule.

Thanks for your feedback!
 
M

Matt Kruse

Robert said:
I would like your or someone else his/her comment about the
synchronization problems using (asynchronous) Ajax.

Here's my comment: The "problems" only exist for people who don't know how
to develop correctly :)
Please read this webpage that describes the problems when using
asynchronous Ajax:
http://softwaredesign.nl/index.php?pageID=34

There are no problems there. Just complaining about the obvious.

There are plenty of ways to work with the async nature of ajax. You could
write a queue in javascript that dispatches only one event at a time. Or you
could create a queue such that ajax calls could be sent many at a time, but
the responses would be queued up until they can be delivered in the correct
order back to the processing javascript. Or you could "lock down"
interaction with the page until the ajax call returns. Or you can create
your UI in such a way that the async nature of the ajax calls doesn't even
matter.

These issues have all been worked out by many people. Articles like the
above just highlight the author's inability to solve basic challenges in
programming. Just look at the author's rant against CSS and it's obvious
that he is a clueless whiner.
 
J

Julian Turner

Robert said:
I would like your or someone else his/her comment about the
synchronization problems using (asynchronous) Ajax. Because for me it
just gives more problems than it solves.

Please read this webpage that describes the problems when using
asynchronous Ajax:
http://softwaredesign.nl/index.php?pageID=34

I am only an amateur with this, but my thoughts are:-

1. The author in that referred article seems to equate AJAX with
asynchronous. See:-

QUOTE: "The idea behind Ajax is not new. Asynchronous communication has
emerged a number of times as the answer to provide responsive user
interfaces."

QUOTE: "However, if there is any dependency whatsoever, you will need
synchronization. Since Javascript offers no synchronization at all,
this translates to "if your Ajax data transmissions have dependencies
you are in deep shit".

But as far as I am aware, AJAX does have a "synchronous" option, albeit
it means that the browser "hangs" when waiting for the response.

2. That article is useful in pointing out potential pitfalls. But I
am not clear what alternatives/solutions the author in that article is
offering, or indeed thinks are possible, for an open distributed
environment like the internet. Yes there are challenges to be faced,
but unless the author has a better idea, we need to engage imagination
and work with what we have I suppose.

3. QUOTE: "Asynchronous communication can work, but it requires
certain synchronization mechanisms. Mechanisms that do not exist in
Javascript. "

I don't think I agree with this. One could perhaps (subject to
limitations as to number of permitted requests at any time) manage
timing issues (if timing is an issue) by creating a request "list",
accessible to the send() the call-back() function of each request.
Each time a request it is made it would be pushed onto the list. When
a request completes, it would be removed from the list. This then could
let you have control such as:-

(a) Only allowing a given request to start or run its call-back() if
all or certain previous requests have completed.

(b) Allowing you to abort certain requests if a particular kind of
request is made or fails.

(c) Allowing you to abort requests if some particular action is
taken by the client.

Admittedly this does not help with the issue of timing of requests
received at the server, athough I would not be so gloomy as to assume
that this could not be overcome.

Regards

Julian Turner
 
L

Laurent Bugnion

Hi,

Julian said:
I am only an amateur with this, but my thoughts are:-

1. The author in that referred article seems to equate AJAX with
asynchronous. See:-

QUOTE: "The idea behind Ajax is not new. Asynchronous communication has
emerged a number of times as the answer to provide responsive user
interfaces."

AJAX stands for Asynchronous JavaScript And Xml, so yes, AJAX is
asynchronous.

It is possible in some implementations to use synchronous requests, but
I would really advise against it. When JavaScript waits for the answer,
the whole JavaScript engine is blocked, nothing else happens until the
answer is back. If the call is made to a remote web server, which in
turn calls another server, the request might take a few seconds at least
to be executed, maybe more, during which the whole page is blocked.

Asynchronous request/responses are not as simple as synchronous, sure,
but it's really not that hard once you understand how it works, and you
model it correctly.

HTH,
Laurent
 
R

Robert

Matt said:
There are no problems there. Just complaining about the obvious.

There are plenty of ways to work with the async nature of ajax.

Is there such a framework around "ajax" that works with this asyn nature?
You could
write a queue in javascript that dispatches only one event at a time. Or you
could create a queue such that ajax calls could be sent many at a time, but
the responses would be queued up until they can be delivered in the correct
order back to the processing javascript.

Don't you mean AND? I mean it is both vital that the requests are
received in the right order by the server AND that the responses are
received back in the right order.
Or you could "lock down"
interaction with the page until the ajax call returns.

If you want to lock it down, can't you just as well use synchronous
requests?
Or you can create
your UI in such a way that the async nature of the ajax calls doesn't even
matter.

Of course. But then requests cannot be dependant. And they often are
dependant.
Just look at the author's rant against CSS and it's obvious
that he is a clueless whiner.

Didn't read that, but come on. CSS is pretty horrible. Sometimes it
takes a lot of effort to find out how something is supposed to work. And
then when you want to use it you find out that each browser implemented
it wrong :) That never would have happened if it were all more
comprehendable and practical.
 
J

Julian Turner

Laurent said:
AJAX stands for Asynchronous JavaScript And Xml, so yes, AJAX is
asynchronous.

Ahh yes, I forgot that was the origin of the anacronym. I guess I just
go the impression that this may lead some to foget that there is also a
synchronous option.
It is possible in some implementations to use synchronous requests, but
I would really advise against it.

Agreed. I look for the asynchronous solution first, and so far have not
needed to call on synchronous.
When JavaScript waits for the answer,
the whole JavaScript engine is blocked, nothing else happens until the
answer is back. If the call is made to a remote web server, which in
turn calls another server, the request might take a few seconds at least
to be executed, maybe more, during which the whole page is blocked.

Agreed. I was making the same point, I hope, when I referred to the
browser "hanging".
Asynchronous request/responses are not as simple as synchronous, sure,
but it's really not that hard once you understand how it works, and you
model it correctly.

Agreed. Again, I was hopefully making the same point.

Best Wishes

Julian Turner
 
R

Richard Cornford

Robert said:
Is there such a framework around "ajax" that works with this
asyn nature?

It is the sort of thing that probably should not be made part of a
general framework anyway. The work involved in handling asynchronous
requests and asynchronous user input in an interactive system far
exceeds what it necessary in a system that is only presenting data to a
user. Imposing the overheads of the first on the second would not be a
sensible thing to be doing. This is an area where application specific
handling is probably called for.
Don't you mean AND? I mean it is both vital that the requests are
received in the right order by the server AND that the responses are
received back in the right order.

It is not vital that responses are received in any order, only that
they are acted upon in a 'correct' order. And the server should not
need to receive requests in any given order, but if it does that just
becomes a matter of sending the next request as a reaction to receiving
the response from the first.
If you want to lock it down, can't you just as well use synchronous
requests?
<snip>

There is little worse you could do. In addition to locking up the
browser and the javascript engine (as mentioned elsewhere), IE has a
habit of crashing if you close it down while it is in the middle of a
synchronous request. But locking up the browser is bad enough.

One of the nicer things about asynchronous requests is you have an
opportunity to do processor intensive tasks, like creating hundreds of
Elements, while you are waiting for responses. With synchronous
requests you have to do that work outside the request/response process,
and lock the browser up even more.

Richard.
 
M

Matt Kruse

Robert said:
I mean it is both vital that the requests are
received in the right order by the server AND that the responses are
received back in the right order.

Not necessarily. Depends on the app.
Of course. But then requests cannot be dependant. And they often are
dependant.

Many "dependencies" exist only in the developer's mind. If you think
differently, you can often get rid of dependencies and instead handle things
in an async way. Not always, but often.
Didn't read that, but come on. CSS is pretty horrible.

It has its quirks and problems. It certainly is not as powerful as it could
be. It certainly isn't implemented as correctly as we'd like. But it's far
from horrible.
Sometimes it
takes a lot of effort to find out how something is supposed to work.
And then when you want to use it you find out that each browser
implemented it wrong :) That never would have happened if it were all
more comprehendable and practical.

The lag of standards behind software is an ongoing problem on the web, and
has contributed greatly to the css incompatabilities that exist. But
Microsoft carries a lot of the blame too. They update browser functionality
rarely (IE6 is ancient), and since it is the most-used browser, CSS often
needs to cater to the lowest common denominator (IE). When IE catches up or
fades in popularity, CSS will be better.

This statement by the author:
CSS promises this goodness for the web: you lay out your page with CSS, it
looks the same in all the browsers.

shows how clueless he is (the statement is absolutely false), so his opinion
on any web technology is immediately questionable.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 1 Jun 2006
11:14:37 remote, seen in Matt Kruse
The TOC is as follows:

1. Always Use 'var'
2. Feature-Detect Rather Than Browser-Detect
3. Use Square Bracket Notation
4. Avoid 'eval'
5. Reference Forms and Form Elements Correctly
6. Avoid 'with' Statements
7. Use onclick In Anchors Instead Of javascript: Psuedo-Protocol
8. Use The Unary + Operator To Cast To Number
9. Avoid document.all
10. Don't Use HTML Comments In Script Blocks
11. Avoid Cluttering The Global Namespace
12. Avoid prototype.js
13. Avoid sync "Ajax" calls
14. Use JSON
15. Use Correct <script> Tags

ISTM that it could be useful to re-post the current TOC each weekend.

Another section, maybe, about not using javascript to do what is better
done in CSS? in others???

The title "Javascript Best Practices" includes all Javascript; but the
TOC seems to have Web javascript only in mind. Some of the entries
apply well to both; others perhaps only to Web. I suggest a rewrite of
title and/or TOC with the existence of WSH javascript firmly in mind, so
that the document properly includes or excludes it.
 
M

Matt

Use The Unary + Operator To TypeConvert To Number

Using parseInt or parseFloat is not considered a "bad" practice, is it?
If it is, please explain.
 
R

Randy Webb

Matt said the following on 6/12/2006 10:52 AM:
Using parseInt or parseFloat is not considered a "bad" practice, is it?
If it is, please explain.

parseInt has it's own problems if people are not aware of the second
parameter. Using the Unary + is considered a Best Practice because it
beats any other method of converting to a Number in Speed comparisons.
 
M

Michael Winter

Using parseInt or parseFloat is not considered a "bad" practice, is
it?

No, but either function can be overkill.

The parseInt function is useful when converting from a base other than
decimal, and both functions are convenient for stripping off trailing
non-numeric characters (for example, units in CSS length values).
However, if a string is known to contain a number (for example, after
validating user input), the unary plus operator (+) is simpler and more
efficient. If one prefers a more verbose approach, the Number
constructor called as a function has the same effect, though it's ever
so slightly slower due to the call overhead.

Mike
 
L

Lasse Reichstein Nielsen

Michael Winter said:
If one prefers a more verbose approach,
the Number constructor called as a function has the same effect,
though it's ever so slightly slower due to the call overhead.

I'm one of those who prefer verbosity in this case. I find
readability, and through it maintainability, more important than
ever so slight performance increases.

"More computing sins are committed in the name of efficiency than for
any other single reason-including blind stupidity" - W.A. Wulf

"...premature optimization is the root of all evil." - Donald Knuth

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Mon, 12 Jun 2006 11:17:44 remote, seen in
Randy Webb said:
Matt said the following on 6/12/2006 10:52 AM:

parseInt has it's own problems if people are not aware of the second
parameter.

it's -> its.
Using the Unary + is considered a Best Practice because it
beats any other method of converting to a Number in Speed comparisons.

No. Using the Unary + is considered a Best Practice because it is
thought to beat any other method of converting to a Number in Speed
comparisons.

Using IE4, go to <URL:http://www.merlyn.demon.co.uk/js-quick.htm> and
press Demo 5 times. Insert in one of the two {} the characters +D0 and
in the other D0.valueOf() and change K=50 to K=500000 (for a 300 MHz
machine; scale as needed). Press Eval and read the value of o appearing
below. I find that the +D0 loop is about 10% slower. Presumably in
this case executing + then calls valueOf().

Of course, it should be tried on other machines and browsers.

There is truth behind your statement; but it does not express exact
truth. Maybe :-

Using the Unary + is considered a Best Practice because it beats any
other method of converting a String to a Number in Speed comparisons.
++++++++
 
E

enaeher

In the long run people who need to work with javascript must benefit
most from acquiring a better understanding of javascript, and that
better understanding will inevitably involve an appreciation of what is
wrong with the whole notion of off-the-shelf javascript libraries, and
particularly the monolithic and framework-style libraries.

Can you elaborate, or point me to a fuller explanation? The only thing
that comes to mind immediately which might make libraries a worse idea
in Javascript than in other languages is the lack of namespaces and
potential for collisions; are there other reasons? The ability to reuse
code seems worth the hassle of taking extra care to avoid name
collisions.

And from the best practices document, regarding eval:
If it exists in your page, there is almost always a more correct way to accomplish what you are
doing. For example, eval is often used by programmers who do not know about using Square
Bracket Notation.

It seems to me that it's most often used to evaluate JSON in response
to an XmlHttpRequest call. Why is this a bad idea? What is the
advantage in using a JSON parser (written in Javascript) rather than
the implementation's implementation of eval? I don't understand the
security concerns that are commonly mentioned; XmlHttpRequests are
directed to a specific URI, which presumably you, the developer,
control, and if someone manages to compromise the server-side code
sufficiently to send malicious Javascript in response to an
XmlHttpRequest surely they can send whatever code they'd like when the
page is being loaded.

--Eli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top