RFD: How To Recognize Bad Javascript Code

  • Thread starter Jeremy J Starcher
  • Start date
J

Jeremy J Starcher

(Request for Discussion)

I've put together a guide that I hope will help novice coders avoid the
same hair pulling that I went through.

I'm open for comments about it.

Have I missed the mark on a point or two?
Have I overlooked something?
Is my basic goal flawed? Is code bad in so many different ways that I
should just pack up shop and forget this?

Or did I do a smashing bang-up job that will keep the new coders away from
the horrors of most online examples and finally end c.l.j's favorite
hobby?(*)



(*) Saying "That's junk! Don't do that!"
 
S

slebetman

For the language="javascript" issue you recommended:
<script type="text/javascript"></script>

Personally I'd recommend just using:
<script></script>

Partly because "text/javascript" is an invalid MIME type, it should be
"application/javascript". But "application/javascript" is invalid
HTML, it MUST be "text/javascript". So best to avoid it altogether and
save keystrokes/bytes.
 
T

Thomas 'PointedEars' Lahn

slebetman said:
For the language="javascript" issue you recommended:
<script type="text/javascript"></script>

Which is correct.
Personally I'd recommend just using:
<script></script>

So you would recommend invalid markup.

http://validator.w3.org/
Partly because "text/javascript" is an invalid MIME type,

It isn't.
it should be "application/javascript".

It shouldn't.
But "application/javascript" is invalid HTML,

It isn't.
it MUST be "text/javascript".

It needs not to.
So best to avoid it altogether and save keystrokes/bytes.

You are completely wrong:

http://pointedears.de/scripts/test/mime-types/

BTW, we discussed this only a few days ago. Please read before you post.


PointedEars
 
R

Richard Cornford

slebetman wrote:
For the language="javascript" issue you recommended:
<script type="text/javascript"></script>

Personally I'd recommend just using:
<script></script>

Which could never be valid (x)HTML mark-up as the TYPE attribute is
required by the pertinent validity rules.
Partly because "text/javascript" is an invalid MIME type,

It is not an "invalid" MIME type. It was a fictional MIME type up until
2006, and then it became an inappropriately labelled "obsolete" MIME
type (inappropriate because it does not make sense to declare something
as obsolete until it is practical to not use it).
it should be "application/javascript".

And it probably will be "application/javascript" at some point in the
relatively distant future when "text/javascript" actually becomes
obsolete.
But "application/javascript" is invalid HTML,

No it is not. The values for the TYPE attribute are externally
referenced from the (x)HTML specifications in a way that implies that
any current MIME type would be valid (and mark-up validators don't check
those external references anyway).
it MUST be "text/javascript".

There certainly is no "MUST" about it. The formulation
TYPE="text/javascript" is used because it is the valid mark-up that has
been observed to be universally successful (or non-problematic). The
odds are that that universal effectiveness results from
"text/javascript" being used as an example value in the HTML
specification, regardless of the fact that at the time there was no MIME
type for javascript.
So best to avoid it altogether and
save keystrokes/bytes.

So it comes down to an appeal to idleness? There may be valid reasons
for abandoning mark-up validity but idleness does not seem like
sufficient reason in itself. (Especially is it is actually being too
idle to write (or go out and find) a macro that will insert the entire
script tag as a result of one action, or use some other similar editor
facility.)

Richard.
 
J

Jeremy J Starcher

Personally I'd recommend just using:
<script></script>

Partly because "text/javascript" is an invalid MIME type, it should be
"application/javascript". But "application/javascript" is invalid
HTML, it MUST be "text/javascript". So best to avoid it altogether and
save keystrokes/bytes.

I had forgotten about "application/javascript" I saw that discussion a
few days ago and made a mental note. Since my mental notes are written in
the sea-shore at low tide -- I forgot.

It is my understanding that this mime type is actually recognized by
anything in the world and has been rushed into service without a valid
reason for the rush.

We hang onto "text/javascript" because pretty much everything supports it
and it still works. Not only works, but works better than its proposed
replacement.
 
T

Thomas 'PointedEars' Lahn

Jeremy said:
I've put together a guide that I hope will help novice coders avoid the
same hair pulling that I went through.

I'm open for comments about it.

Have I missed the mark on a point or two?
Have I overlooked something?

Plenty.

1. "Depreciated script tag usage"

a. The word you were looking for is _deprecated_, not "depreciated".

b. The term you were looking for is `script' _element_, not "tag".
Elements consist of tags (start tag, close tag) and content:

http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.1

c. Your example `script' elements are empty where they should have
content. At least that should be indicated in some way.

d. "JavaScript1.2" actually means something in NN4; ask Google.
I have never seen anyone using "JavaScript1.3", though.

2. 'Using "href:javascript"'

| Using the pseudo-protocol javascript in the href is never valid. Not
| only is such code not valid HTML, [...]

Wrong. The value of the `href' attribute is of type URI. If
`javascript:' syntax would be written as an URI, it would certainly
be valid there. One point of recommending against `javascript:'
there is that

| it cannot provide a fallback to browsers not running Javascript.

There are other points that I have also mentioned in my FAQ notes last
year. There are also exceptions to be made in special cases.

3. "Excessive use document.write"

should read "Excessive use *of* document.write()".

A recommendation for a viable alternative is missing. Consider this:

<script type="text/javascript">
if (NN4 || IE4)
{
document.write(
new Array(
'<ul>',
' <li><a href="Search.html">Search<\/a><\/li>',
' <li><a href="Order.html">Order<\/a><\/li>');
' <li><a href="Help.html">Help<\/a><\/li>');
'<\/ul>'
).join("")
);
}
</script>

4. 'Not ending lines in a semi-colon ";"'

The argument in favor of the trailing `;' is flawed in two regards:
a) not every line should be ended with a semicolon but every *statement*;
b) minifiers should not be used. See previous discussions.

5. "Use of eval"

| Using eval to parse JSON works well. While there are some security
| concerns, they can be easily addressed.

There are two other uses where using eval() is considered appropriate.
One is making arbitrary computations with user input, the other is
hiding code from script engines that consider it to be syntactically
invalid because they do not support the corresponding language feature.

A reasoning for the statement that the security concerns could be
easily addressed is missing.

6. "Browser sniffing"

You describe the goal of that -- "to tell which browser the code is
running on" to be "good", and I don't agree. Web developers should
avoid writing for a specific user agent.

7. "Web pages that do not include a DOCTYPE and/or do not validate"

| Internet Explorer provides a way to identify itself that does not
| interfer with other browsers. Some web developers use this to work
| around bugs in IE's handling of style sheets or to import
| compability code. Other web developers regard this is an evil crutch.

The argument against Conditional Comments is not sound, at least not
for IE-specific workarounds. CCs are valid SGML markup.
Is my basic goal flawed?

I don't think so. I think it would make a fine addition to the FAQ after
careful evaluation.
Is code bad in so many different ways

You can bet on that.
that I should just pack up shop and forget this?

No, it's a good start.
Or did I do a smashing bang-up job that will keep the new coders away from
the horrors of most online examples and finally end c.l.j's favorite
hobby?(*)

Hardly.


PointedEars
 
J

Jeremy J Starcher

Plenty.

1. "Depreciated script tag usage"

a. The word you were looking for is _deprecated_, not "depreciated".

Absolutely correct. Thought I spell-checked everything. I'll fix that.
b. The term you were looking for is `script' _element_, not "tag".
Elements consist of tags (start tag, close tag) and content:

http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.1

Once again correct. I've let myself get a bit sloppy in speech.
c. Your example `script' elements are empty where they should have
content. At least that should be indicated in some way.

Hadn't thought of that, but it makes sense.
d. "JavaScript1.2" actually means something in NN4; ask Google.
I have never seen anyone using "JavaScript1.3", though.

I didn't know if that was backwards compatible to browsers today or not.
If memory serves me correctly, it changes some of the array methods.

2. 'Using "href:javascript"'

| Using the pseudo-protocol javascript in the href is never valid. Not
| only is such code not valid HTML, [...]

Wrong. The value of the `href' attribute is of type URI. If
`javascript:' syntax would be written as an URI, it would certainly
be valid there. One point of recommending against `javascript:'
there is that

| it cannot provide a fallback to browsers not running Javascript.

There are other points that I have also mentioned in my FAQ notes last
year. There are also exceptions to be made in special cases.

Hmmm... This point has me thinking now. I'll have to ponder the best way
to phrase the URI issue. "Valid, but not recommended" perhaps.

I'll try and find your FAQ notes. If you are feeling generous I'll take a
donated URL to it.
3. "Excessive use document.write"

should read "Excessive use *of* document.write()".

Agreed, once again. Bad proofreading on my part again.
A recommendation for a viable alternative is missing. Consider this:

<script type="text/javascript">
if (NN4 || IE4)
{
document.write(
new Array(
'<ul>',
' <li><a href="Search.html">Search<\/a><\/li>',
' <li><a href="Order.html">Order<\/a><\/li>');
' <li><a href="Help.html">Help<\/a><\/li>');
'<\/ul>'
).join("")
);
}
</script>

I'll agree that is better than the table design, but I was trying to
indicate that using Javascript for putting a navigation bar on the screen
shouldn't be done. Augmenting one would be OK.

Perhaps a different example would be better. Using Javascript to show a
print button or something.
4. 'Not ending lines in a semi-colon ";"'

The argument in favor of the trailing `;' is flawed in two regards:
a) not every line should be ended with a semicolon but every *statement*;

I code in C. I know that. Somewhere it got lost between brain and
keyboard. Maybe I've been using "one statement per line" scripting
languages too much.
b) minifiers should not be used. See previous discussions.

I knew that was going to come up. I'm tempted to yank that whole section
out, except that style-wise I -really- like having the semicolon there.
Code without it grates on me.
5. "Use of eval"

| Using eval to parse JSON works well. While there are some security
| concerns, they can be easily addressed.

There are two other uses where using eval() is considered appropriate.
One is making arbitrary computations with user input,

Yes, I should mention that. While I've only seen it used for "trivial"
calculator applications, I suppose it would be the basis for an Javascript
spreadsheet or something.
the other is
hiding code from script engines that consider it to be syntactically
invalid because they do not support the corresponding language feature.

Oh.. there is an idea. That is the second new thought you've tossed into
my head here. I'm picturing one code branch that runs slowly with a dozen
checks to assert all values are within range and a second code branch
using try/catch. The try/catch is faster when available.

Is that the kind of thing you mean?

A reasoning for the statement that the security concerns could be
easily addressed is missing.

6. "Browser sniffing"

You describe the goal of that -- "to tell which browser the code is
running on" to be "good", and I don't agree. Web developers should
avoid writing for a specific user agent.

Poor wording on my part. No, its not good. Recognizing that all the
world is not IE and that differences exist *is* good.
7. "Web pages that do not include a DOCTYPE and/or do not validate"

| Internet Explorer provides a way to identify itself that does not
| interfer with other browsers. Some web developers use this to work
| around bugs in IE's handling of style sheets or to import
| compability code. Other web developers regard this is an evil crutch.

The argument against Conditional Comments is not sound, at least not
for IE-specific workarounds. CCs are valid SGML markup.

I agree. I worked very hard on my wording to remain as neutral as
possible, I'll have to find a way to phrase "Other web developers regard
this is an evil crutch -- but they are wrong" a little more gently.
PointedEars

Thank you for your advice. There are a handful of people whom I had hoped
would take time to respond because I recognize their knowledge and skill
greatly exceeded my own. You are one of them.

Not to say others aren't welcome to respond. Other beginners, no doubt,
have their own lessons we can learn from.

I'll try to update that page later on today, after I've had a chance to
think about some of the things mentioned so far.
 
A

Anthony Levensalor

Thomas 'PointedEars' Lahn posted :

[snip]
1. "Depreciated script tag usage"

a. The word you were looking for is _deprecated_, not "depreciated".


Well, if we're being anal, Thomas, "_deprecated_" is not a word.
"deprecated" is, though.
b. The term you were looking for is `script' _element_, not "tag".
Elements consist of tags (start tag, close tag) and content:

http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.1


Funny thing is, I looked that page up and down buddy, and I didn't see
anything about a script _element_ anywhere. Maybe your underscore is broken.
c. Your example `script' elements are empty where they should have
content. At least that should be indicated in some way.


Pretty sure that's already been under discussion regarding the type
attribute. Please read before you post, as you like to say.
One point of recommending against `javascript:'
there is that

| it cannot provide a fallback to browsers not running Javascript.

There are other points that I have also mentioned in my FAQ notes last
year. There are also exceptions to be made in special cases.


You know what would be even more helpful? A link or even a hint about
where your big ole FAQ is for those of us not arrogant enough to read
your mind.
3. "Excessive use document.write"

should read "Excessive use *of* document.write()".


Are you a programmer or an English teacher? Oh, you're both! That would
explain a whole bunch.
A recommendation for a viable alternative is missing.


Like the link to your FAQ, Mr. Kettle?


[snip]



This, right here, this is why people get irritated with you, I think.
Maybe you just like being a pompous arrogant , I dunno, but most other
people don't care for it. You lack that internal filter that says "don't
say that, that's what a pontificating, unmitigated ass would say"

~A!
 
T

Thomas 'PointedEars' Lahn

Anthony said:
Thomas 'PointedEars' Lahn posted :
[snip]
1. "Depreciated script tag usage"

a. The word you were looking for is _deprecated_, not "depreciated".


Well, if we're being anal, Thomas, "_deprecated_" is not a word.
"deprecated" is, though.

Enclosing text with the underline character is used in Usenet to mark text
as an underlined correction because in plain text the usual text formatting
is not available. Your Thunderbird and mine even have a feature implemented
that formats text that way if the parser encounters that syntax. The same
goes for `*...*' (bold, usually meant as emphasis) and `/.../' (italic, also
emphasis).
Funny thing is, I looked that page up and down buddy, and I didn't see
anything about a script _element_ anywhere. Maybe your underscore is broken.

Maybe you are an idiot. (See, *now* I said it.)
Pretty sure that's already been under discussion regarding the type
attribute. Please read before you post, as you like to say.

The reaction of the OP says otherwise. So much for reading.
One point of recommending against `javascript:'
there is that

| it cannot provide a fallback to browsers not running Javascript.

There are other points that I have also mentioned in my FAQ notes last
year. There are also exceptions to be made in special cases.

You know what would be even more helpful? A link or even a hint about
where your big ole FAQ is for those of us not arrogant enough to read
your mind.

[more flames]

*PLONK*


PointedEars
 
T

Thomas 'PointedEars' Lahn

Jeremy said:
I didn't know if that was backwards compatible to browsers today or not.
If memory serves me correctly, it changes some of the array methods.

Care to elaborate?
2. 'Using "href:javascript"'

[...]
There are other points that I have also mentioned in my FAQ notes last
year. There are also exceptions to be made in special cases.

[...]
I'll try and find your FAQ notes. If you are feeling generous I'll take a
donated URL to it.

I finally found the Message-ID in my Sent folder:

Ouch. Don't consider the last two lines as they are. Copy-paste error.
Replace them with

' <li><a href="Order.html">Order<\/a><\/li>',
' said:
I'll agree that is better than the table design, but I was trying to
indicate that using Javascript for putting a navigation bar on the screen
shouldn't be done. Augmenting one would be OK.

That would depend on what kind of navigation bar it would be. If it
requires client-side script support as it provides additional features,
then there is nothing wrong in writing it dynamically.
Perhaps a different example would be better. Using Javascript to show a
print button or something.

That would be another example.
5. "Use of eval"

| Using eval to parse JSON works well. While there are some security
| concerns, they can be easily addressed.

There are two other uses where using eval() is considered appropriate.
[...]
the other is
hiding code from script engines that consider it to be syntactically
invalid because they do not support the corresponding language feature.

Oh.. there is an idea. That is the second new thought you've tossed into
my head here. I'm picturing one code branch that runs slowly with a dozen
checks to assert all values are within range and a second code branch
using try/catch. The try/catch is faster when available.

Is that the kind of thing you mean?

Not quite. For example, you would need eval() to hide try...catch from
engines that don't support it but where it is necessary to use it. With
XHR, that would be handling exceptions in creating the ActiveXObject object.
I'll toss in this link: <URL: http://www.json.org/json2.js > In my
reading, I haven't heard of anyone finding holes in it.

I know the JSON reference implementation but I don't see how that would
provide a reason for your statement that it would be easy to address
security concerns that using eval() with JSON would introduce. Care to
elaborate?


PointedEars
 
J

Jeremy J Starcher

HTML Comments.
Will cause problems when XHTML is used.

Noted. Thanks.
Script tag usage.
text/javascript is an obsolete (although valid) MIME type.

Recently found the discussion on that one. It will be addressed.
href:javascript.
Drop #1, they all fall into the "Too stupid to know better" category.

If this were directed at coders, I'd agree. I'm trying to aim this paper
more at people getting into looking at/learning Javascript and maybe help
them avoid a lot of the crap I waded through.

document.write.
Avoid it. Period.
Tables produced with document.write are indicative of an idiot programmer.
Buttons/links? document.createElement, .appendChild, no document.write

I 99.9% agree with you. I use it once in my code to hide tabs when
Javascript is enabled. Without Javascript defaults to a giant ordered
list. Any other method I found causes a screen flicker as the <ul> first
renders and then is reshaped.

<script type="text/javascript"> document.write('<style
type="text/css">.tabber{display:none;} said:
Local vars.
No example of a correct way.
Touche.

Line ending semicolons.
That entire section is incorrect.
Do you have a URL for the assertion that Brendan Eich (and others)
intentionally left out statement ending semi-colons to "make it
easier to learn"?
As for minification, that is an indication of bad coding practices.

Ok, Ok -- it gets ripped. Was a coin toss on it going in first time round.
Use of eval.
The use of eval itself usually indicates bad coding, but not always.
Whether it is a bad use of it or not depends on how it is used.
And a beginner can't possibly know.

<snip>
Thomas had a few comments that have been thinking over the eval issue.
I'm still pondering.. but you bring up valid points as well.

Browser detection.
Spelling error with interfer versus interfere. *nods*


DOCTYPE.
No version of IE, not just IE7, handles it that way.
Meant to say that.
The use of the "with" operator.
Food for thought. I've avoided the with operator since the ancient days
of Pascal, so I don't even see code in it. Barely aware that JS had one.
Use of "new Function".
I don't see this one too often.
There are, inevitably, more things you didn't cover.

Personally, I think a "Best Methods" document is of far more value than
a "Bad Methods" document. Then, you aren't showing people bad ways to do
things, you are showing them the best ways to do things. And even though
I don't agree, totally, with Matt's, I keep it in my signature for that
very reason.

I won't quibble the need for a "Best Methods" document, but I was trying
to fill a different need. I see a "Best Methods" as a document aimed at
coders. I'm trying to aim at people who don't code yet.

It is my goal to have an easy-to-understand list of things that should
throw up red flags when you see them in code. If too many code snippets
have these red flags, skip onto the next site.

Not to name names, but had I the skill to recognize
<URL: http://www.dynamicdrive.com/ > for what it was, I wouldn't have had
to unlearn so much.
 
A

Anthony Levensalor

Thomas 'PointedEars' Lahn posted :

Enclosing text with the underline character is used in Usenet to mark text
as an underlined correction because in plain text the usual text formatting
is not available. Your Thunderbird and mine even have a feature implemented
that formats text that way if the parser encounters that syntax. The same
goes for `*...*' (bold, usually meant as emphasis) and `/.../' (italic, also
emphasis).


I know. ;)

Maybe you are an idiot. (See, *now* I said it.)


Could be, definitely. I've been called worse by better.

The reaction of the OP says otherwise. So much for reading.


Yup, I got thumped on this one.




That actually wasn't meant to be a flame. That was meant to help you
become someone we could all adore.


~A!
 
A

Anthony Levensalor

Jeremy J Starcher posted :

This, right here, this is why people get irritated with you, I think.
Maybe you just like being a pompous arrogant , I dunno, but most other
people don't care for it. You lack that internal filter that says "don't
say that, that's what a pontificating, unmitigated ass would say"

[start way off-topic]

While I don't know Thomas "PointedEars" personally, and won't speak for
him I do know his personality type. Rather than defend him in particular
allow me to say a few words for the entire "have-no-people skills but
really good with machine" type people.


[snip]


Jerry,

First, I liked your doc, and the comments on it so far have taught me a
lot. I haven't commented because I lack the experience to intelligently
do so

As for Thomas, I was sniping. He irritates me. I really didn't want to
do anything in that post but irritate him, apologies for sidetracking
the discussion of your work. I hate to see someone put so much effort
and labor into something to have someone be so callous about it.

~A!
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
am.me.not.com>, Tue, 1 Jan 2008 12:59:00, Jeremy J Starcher
I'll try and find your FAQ notes. If you are feeling generous I'll take a
donated URL to it.

It is commonly considered polite and prudent to read a newsgroup for a
while, and to seek its FAQ, *before* posting to it. The FAQ of this
group is readily found by reading the group (and otherwise), and links
to its Notes.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>
, Tue, 1 Jan 2008 13:13:51, Anthony Levensalor
Thomas 'PointedEars' Lahn posted :
Are you a programmer or an English teacher? Oh, you're both! That would
explain a whole bunch.

It is commonly considered polite and prudent to read a newsgroup for a
while *before* posting to it. If you had done that, you would have
known about Thomas Lahn.
 
A

Anthony Levensalor

Jeremy J Starcher posted :

Not to name names, but had I the skill to recognize
<URL: http://www.dynamicdrive.com/ > for what it was, I wouldn't have had
to unlearn so much.


I'm just heading down that "re-learning everything I thought I knew"
path in Javascript because of that and sites like it. Thanks for not
wanting anyone else to go through this, it's not fun.

~A!
 
T

Thomas 'PointedEars' Lahn

Anthony said:
First, I liked your doc, and the comments on it so far have taught me a
lot.

But you despise the people that made them? Something doesn't add up here.
I haven't commented because I lack the experience to intelligently do so

That much is obvious.
As for Thomas, I was sniping. He irritates me. I really didn't want to do
anything in that post but irritate him,

If you do think that could do any good, you are using the wrong medium.
You are back out of my killfile, for now, but scored Lowest.
apologies for sidetracking the discussion of your work.

You are apologizing to the wrong person.
I hate to see someone put so much effort and labor into something to have
someone be so callous about it.

You missed:

,-<[email protected]>
|
| [...]
| > Is my basic goal flawed?
|
| I don't think so. I think it would make a fine addition to the FAQ after
| careful evaluation.
|
| > Is code bad in so many different ways
|
| You can bet on that.
|
| > that I should just pack up shop and forget this?
|
| No, it's a good start.


PointedEars
 

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,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top