As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been exploring different methods to clean up and test my JavaScript. I figured just like any other language one way to get better is to read good code. jQuery is very popular so it must have a certain degree of good coding.
So why when I run jQuery through JSLint's validation it gives me this message:
Error:
Problem at line 18 character 5:
Expected an identifier and instead saw
'undefined' (a reserved word).
undefined,
Problem at line 24 character 27:
Missing semicolon.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Expected an identifier and instead saw
'='.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Stopping, unable to continue. (0%
scanned).
This was done using JSLint and jquery-1.3.1.js
JSLint tests one particular person's (Douglas Crockford) opinions regarding what makes good JavaScript code. Crockford is very good, but some of his opinions are anal retentive at best, like the underscore rule, or the use of the increment/decrement operators.
Many of the issues being tagged by JSLint in the above output are issues that Crockford feels leads to difficult to maintain code, or they are things that he feels has led him to doing 'clever' things in the past that can be hard to maintain.
There are some things Crockford identifies as errors that I agree with though, like the missing semicolons thing. Dropping semicolons forces the browser to guess where to insert the end-of-statement token, and that can sometimes be dangerous (it's always slower). And several of those errors are related to JSLint not expecting or supporting multiple assignments like jQuery does on line 24.
If you've got a question about a JSLint error, e-mail Crockford, he's really good about replying, and with his reply, you'll at least know why JSLint was implemented that way.
Oh, and just because a library is popular doesn't mean it's code is any good. JQuery is popular because it's a relatively fast, easy to use library. That it's well implemented is rather inconsequential to it's popularity among many. However, you should certainly be reading more code, we all should.
JSLint can be very helpful in identifying problems with the code, even if JQuery doesn't pass the standards it desires.
JSLint helps you catch problems, it isn't a test of validity or a replacement for thinking. jQuery is pretty advanced as js goes, which makes such a result understandable. I mean the first couple of lines are speed hacks, no wonder the most rigid js parser is going have a couple of errors.
In any case, the assumption that popular code is perfectly correct code or even 'good' is flawed. JQuery code is good, and you can learn a lot of from reading it. You should still run your stuff through JSLint, if only because it's good to hear another opinion on what you've written.
From JSLint's description:
JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.
"jQuery is very popular so it must have a certain degree of good coding."
One would like to hope this is the case with jQuery, but unfortunately it's not really true. jQuery is useful and popular, but it is not a well written JavaScript library. David Mark recently posted a scathing critique of jQuery in comp.lang.javascript that examines a large number of examples of the poor code found in jQuery:
http://groups.google.com/group/comp.lang.javascript/msg/37cb11852d7ca75c?hl=en&
If you're not actively developing jQuery itself, why even run JSLint over it at all? If it works, it works, and you don't have to worry about it.
The jQuery developers' goals are not the same as your goals. jQuery is built for speed and compactness and achieving those goals trumps readability and maintainability.
Crockford's tests in JSLint have more to do with achieving something that he would feel comfortable taking home to meet his mother, which is a valid concern if you will be married to your code for some time.
The purpose of JsLint is clearly stated in the FAQ [1]:
"JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language."
Now if you are confused: ECMA3 is already a subset of the JS capabilities provided by any of todays JS interpreters (see [2] for an overview of the relation between JavasScript and ECMAScript versions)
To answer the quesition "what good is JSlint":
* use JsLint to verify you are using a "safe" subset of Javascript that is unlikly to break accross JS implementations.
* use Jslint to verify you followed the crockford code conventions [4]
[1] http://www.jslint.com/lint.html
[2] https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/JavaScript_Overview#Relationship_between_JavaScript_Versions_and_ECMAScript_Editions
[3] https://developer.mozilla.org/en/New_in_JavaScript_1.7#Avoiding_temporary_variables
[4] http://javascript.crockford.com/code.html
I've found one case where JSLint is very, very useful: when you grab one of those big-arse libraries that float around the 'Net, then another, then again one other, you soon find yourself loading 50k of Javascript on every new page load (caching may help, but it's not a cure-all solution).
What would you do then? Compress those libraries. But your host doesn't do compression for non-html file! So what? You use a Javascript compressor.
The best I've found is Dean Edward's; I used it to compress John Fraser's Showdown (a Markdown for Javascript library), but unfortunately, the compression broke the code. Since Showdown isn't supported anymore, I had to correct it myself - and JSlint was invaluable for that.
In short, JSlint is useful to prepare your JS code for heavy duty compression.
If you like to daisy-chain methods like jQuery allows you, you might appreciate YUI3.
JQuery is of course not the best thing in the world. That's already clear when you look at the notation. The dollar parentheses combination is really bad for your eyes. Programming should be clear and simple. JQuery is far from that. That reason is enough for me not to use it. That it's not properly written doesn't surprise me and only underscores my thoughts on this JavaScript library.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Edit: I recently learned about a project called CommonMark, which
correctly identifies and deals with the ambiguities in the original
Markdown specification. http://commonmark.org/ It has great C# library
support.
You can find the syntax here.
The source that follows with the download is written in Perl, which I have no intentions of honoring. It is riddled with regular expressions, and it relies on MD5 hashes to escape certain characters. Something is just wrong about that!
I'm about to hard code a parser for Markdown. What is experience with this?
If you don't have anything meaningful to say about the actual parsing of Markdown, spare me the time. (This might sound harsh, but yes, I'm looking for insight, not a solution, that is, a third-party library).
To help a bit with the answers, regular expressions are meant to identify patterns! NOT to parse an entire grammar. That people consider doing so is foobar.
If you think about Markdown, it's fundamentally based around the concept of paragraphs.
As such, a reasonable approach might be to split the input into paragraphs.
There are many kinds of paragraphs, for example, heading, text, list, blockquote, and code.
The challenge is thus to identify these paragraphs and in what context they occur.
I'll be back with a solution, once I find it's worthy to be shared.
The only markdown implementation I know of, that uses an actual parser, is Jon MacFarleane’s peg-markdown. Its parser is based on a Parsing Expression Grammar parser generator called peg.
EDIT: Mauricio Fernandez recently released his Simple Markup Markdown parser, which he wrote as part of his OcsiBlog Weblog Engine. Because the parser is written in OCaml, it is extremely simple and short (268 SLOC for the parser, 43 SLOC for the HTML emitter), yet blazingly fast (20% faster than discount (written in hand-optimized C) and sixhundred times faster than BlueCloth (Ruby)), despite the fact that it isn't even optimized for performance yet. Because it is only intended for internal use by Mauricio himself for his weblog, there are a few deviations from the official Markdown specification, but Mauricio has created a branch which reverts most of those changes.
I released a new parser-based Markdown Java implementation last week, called pegdown.
pegdown uses a PEG parser to first build an abstract syntax tree, which is subsequently written out to HTML. As such it is quite clean and much easier to read, maintain and extend than a regex based approach.
The PEG grammar is based on John MacFarlanes C implementation "peg-markdown".
Maybe something of interest to you...
If I was to try to parse markdown (and its extension Markdown extra) I think I would try to use a state machine and parse it one char at a time, linking together some internal structures representing bits of text as I go along then, once all is parsed, generating the output from the objects all stringed together.
Basically, I'd build a mini-DOM-like tree as I read the input file.
To generate an output, I would just traverse the tree and output HTML or anything else (PS, LaTex, RTF,...)
Things that can increase complexity:
The fact that you can mix HTML and markdown, although the rule could be easy to implement: just ignore anything that's between two balanced tags and output it verbatim.
URLs and notes can have their reference at the bottom of the text. Using data structures for hyperlinks could simply record something like:
[my text to a link][linkkey]
results in a structure like:
URLStructure:
| InnerText : "my text to a link"
| Key : "linkkey"
| URL : <null>
Headers can be defined with an underline, that could force us to use a simple data structure for a generic paragraph and modify its properties as we read the file:
ParagraphStructure:
| InnerText : the current paragraph text
| (beginning of line until end of line).
| HeadingLevel : <null> or 1-4 when we can assess
| that paragraph heading level, if any.
Anyway, just some thoughts.
I'm sure that there are many small details to take care of and I'm pretty sure that Regexes could become handy during the process.
After all, they were meant to process text.
I'd probably read the syntax specification enough times to know it, and get a feel for how to parse it.
Reading the existing parser code is of course brilliant, both to see what seems to be the main source of complexity, and if any special clever tricks are being used. The use of MD5 checksumming seems a bit weird, but I haven't studied the code enough to understand why it's being done. A comment in a routine called _EscapeSpecialChars() states:
We're replacing each such character with its corresponding MD5 checksum value;
this is likely overkill, but it should prevent us from colliding with the escape
values by accident.
Replacing a single character by a full MD5 does seem extravagant, but perhaps it really makes sense.
Of course, it'd be clever to consider creating a "true" syntax, for a tool such as Flex to get out of the regex bog.
If Perl isn't your thing, there are Markdown implementations in at least 10 other languages. They probably don't all have 100% compatibility, but tend to be pretty close.
MarkdownPapers is another Java implementation whose parser is defined in a JavaCC grammar.
If you are using a programming language that has more than three other
users, you should be able to find a library to parse it for you. A
quick Google-ing reveals libraries for CL, Haskell, Python,
JavaScript, Ruby, and so on. It is highly unlikely that you will need
to reinvent this wheel.
If you really have to write it from scratch, I recommend writing a
proper parser. With this technique, you won't have to escape things
with MD5 hashes. (I agree that if you have to do something like this,
it's time to reconsider your design.)
There are libraries available in a number of languages, including php, ruby, java, c#, javascript. I'd suggest looking at some of these for ideas.
It depends on which language you wish to use, for the best way to implement it, there will be idiomatic and non idiomatic ways to do it.
Regexes work in perl, because perl and regex are best friends.
Markdown is a JAWL (just another wiki language)
There are plenty of open source wiki's out there that you can examine the code of the parser. Most use REGEX
Check out the screwturn wiki, is has an interesting multi pass formatter pipeline, a very nice technique - see /core/Formatter.cs and /core/FormatterPipeline.cs
Best is to use/join an existing project, these sorts of things are always much harder than they appear
Here you can find a JavaScript-implementation of Markdown. It also relies heavily on regular expressions, as this is just the fastest and easiest way to parse the text.
But it spares the MD5 part.
I cannot help directly with the coding of the parsing, but maybe this link can help you one way or another.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been thinking a lot about the way that jQuery is implemented in Javascript code. Libraries such as jQuery and Prototype bind to an alias by default; for these examples, they use the dollar sign $. (Underscore, appropriately, uses an underscore character _.)
I understand how this works. I also understand that many libraries provide a noConflict mode.
My question is, why do these libraries use an alias by default?
From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial. (Honestly - I'm a little biased, because I don't have issues typing long variable names.) I thought that maybe it was for filesize purposes, but with the proliferation of minifiers, it seems like it'd be a moot point (and a form of premature optimization).
On the flip side, the aliases seem to cause a lot of confusion for people using these libraries.
Now, I'm not really arguing against the use of aliases - I'm just wondering why it's the default option for these libraries. Currently, to avoid an alias, we explicitly have to declare that we don't want to use it. Are there specific benefits that I'm missing about the use of aliases for library calls? The only advantage that I could readily think of is if you somehow wrote cross-library code - to swap libraries, you simply swap the alias. I don't think I've ever seen this done, though.
Anyone know the reasoning behind this? I, for one, would really love to know.
"From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial."
That's what the people who designed VB thought too. "What's this
for (int i=0; i<10;i+=2){
}
Stuff! What's wrong with:
For i as Integer = 0 To 10 Step 2
Next i
So I save 13 keystrokes! That's trivial."
It's not trivial when this is what we do all. day. long.
Take the jQuery Cycle plugin: http://malsup.github.com/jquery.cycle.all.js. It has 400 instances of $. If you were to use jQuery instead of $, that would be an extra 2000 keystrokes. It's the reason why IDEs now perform autocomplete of parens, etc. etc. etc.
Using jQuery and Prototype together is not good idea. Ideally there must be only 1 javascript framework for the site, and a lot of calls to it. So the best (default) choice is to use shorthand alias for it's main function.
Anyway, if you need to use several libraries/frameworks together on the same page, and you want to avoid conflicts, you can use noConflict mode.
The problem with writing my own Markdown parser in Clojure is that Markdown is not a well-specified language. There is no "official" grammar, just an informal "Here's how it works" description and a really ugly reference implementation in Perl.
http://briancarper.net/blog/415/
I can see Gruber's specification here and the implementation here.
This is an implementation that wins the google ranking test here
Then there is peg-markdown which appears to solve the 'there is no grammar' problem - but is not the canonical implementation.
My question is - what is the canonical implementation of markdown? (The one that everybody says defines the standard).
EDIT:
I acknowledge that "there is no canonical standard". I'm looking for the next best thing.
The answer seems to be showdown.js, but there are problems with it.
(using the definition of canonical being the one that everybody says defines the standard).
It gets referenced here and on github here.
I'll throw in pagedown as well (as aluded to by #deceze) because it appears to fix the bugs in showdown and be a little closer to Gruber's original.
I believe Gruber's is the original and sort-of-canonical (see, for example, his 'Introducing Markdown'), and then people have extended it from there. I think some extensions are more common than others though, so it's probably worth seeing what a few well-used packages have over his original.
The CommonMark project attempts to address some of the issues of the Markdown specification, in particular some ambiguities. It comes with a reference implementation, but that's obviously just the reference implementation for CommonMark, not for Markdown in general. It may become the de-facto standard in years to come, since some major users are involved in that project, but it might as well become just another dialect among many, in which case the reference implementation would add little value.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.