views:

629

answers:

7

I have been in the process of learning Javascript to complement ASP.NET. I have a strong background in general programming, and have always been an advocate of disciplined practices and good hygiene to reduce the error count in code.

However, the language that Javascript is seems to make this very difficult. Its dynamic and interpreted nature seem to push error detection to the last point possible in the cycle. For example, syntax errors can get caught as late as the point when the code is actually executed, rather than before it is run as would be the case in a more static language. Similarly the soft type system is a minefield of potential hidden errors. Although you can represent object oriented design patterns in the language, it almost seems like they have made it as hard as possible to do so with little in the way of syntactic support.

This is compounded by the fact that Javascript seems to attract a sloppy mindset, and a lot of newbie programmers who confuse conscision and cleverness with quality (and I am not referring to minimized code, but examples of putatively good programming.) I Feel like I am reading entries in the obfuscated C contest sometimes.

Of course I also recognize that there are a lot of assets to Javascript that makes it powerful and extensible. Some of the fluid functional like techniques in, for example, jquery are very attractive.

I guess my question then is this: how do you write quality javascript? What tools, practices, idioms, debugging and logging libraries and so forth do you incorporate to reduce the bug count in your javascript applications? Are there web sites or discussion groups that focus on bug free javascript rather than cute programming hacks?

A: 

Use an IDE to prevent for types and names error.

I had a hard time developing javascript applications because of the weakness of the classes and the types, but since I use Netbeans to develop, the Type checking and method existence is made automatically.

However, you have to code in a way your IDE can recognize what kind of objects you create. I use the prototype attribute and class initializers to create my classes, and forbid myself of creating methods and properties after the initialization of an object.

kbok
+12  A: 

My approach:

  • don't treat the language as a class-based OO language
  • explore the functional traits (you can offload a lot of primitive ops into prepackaged functions)
  • don't conflate the language with the browser environment
  • write unit tests

For example, syntax errors can get caught as late as the point when the code is actually executed, rather than before it is run as would be the case in a more static language.

That's expected from a language without separate compilation. Nothing prevents you from using a lint-like program.

just somebody
+1 for the first point. The OO mindset does not port very well to javascript as it stands.
harpo
Well, it does work, but sometimes it's overly complex design that makes it a bear to work with. Simple projects may work out well, but I find the larger you get, the more it ties you down. Sometimes it's easier to deal with Javascript as if it were a functional language.
Andir
Disagree with point 1, the OO features of javascript are valuable for the purposes of encapsulation and seperation of concerns. The first point left unclarified will steer people away from creating classes with encapsulated logic and further lead to a crowded global namespace. Devs should also get in the habit of writing javascript libraries as self-contained and not expecting dependencies to be referenced/declared elsewhere in another file. Dependencies should be constructor or parameter injected into a library object/method, etc.
David
@David: I think that mainly goes along with the point below this (at the time of writing this comment) about namespacing. While I'm not sure I like the notion of namespacing with "static" values, it's better than none. I do like creating "class" like objects where you define this.myFunction = function(){} within functions, but I try to steer clear of sometimes overly confusing prototyping.
Andir
+1  A: 

Nobody writes high quality software straight way in any language, even the experienced programmers in some other language.So I can't answer that part.

But i can recommend you to use JQuery,mootools and Yahoo UI and various frameworks of javascript.Play with them and look at the source of these javascript libraries.Read this book, JavaScript: The Definitive Guide by David Flanagan and read crockford blog

Srinivas Reddy Thatiparthy
+2  A: 

Normally I don't do this, but since the question has a fairly broad scope, I'm going to recommend a couple of books:

Javascript, the Definitive Guide, 5th Edition
Javascript, the Good Parts

I would imagine that, after reading these two books, you would have a very good grasp on what best practices are.

I'm not sure what to tell you about the newbies and sloppy programmers. You can only control you. You might try recommending these two books to them.

Robert Harvey
+29  A: 

Bonus: Avoid gotchas.

galambalazs
functional? please don't confuse things!!! http://en.wikipedia.org/wiki/Functional_programming
frunsi
**"A moderator, my kingdom for a moderator."** Have you read what you've just posted? *"Programming in a functional style can also be accomplished in languages that aren't specifically designed for functional programming.... Javascript, one of the most widely employed languages today, incorporates functional programming capabilities"*
galambalazs
I don't care if you downvote every post of mine, but please for the community sake, don't confuse others with your misconceptions.
galambalazs
No, really, lets stay on topic and please read the link: "functional" is different that what you might expect.
frunsi
I guess you haven't got enough time reading the link for yourself, because you were so busy trying to find a way to press downvoting 10x. I'm done. Only a moderator can clean your mess.
galambalazs
+2  A: 
  • Syntax Errors: Code in any single Javascript file or <script> tag will not be executed if it contains syntax errors. Other sources of Javascript will still run, but this is expected behavior of an interpreted language whose source code is loaded over a high latency network. Waiting until every last bit of code is in memory would be wasteful. However most browsers only seem to report the first syntax error found (not sure if this is normal for interperted languages) in any one script source.

  • Soft Type System: Just be sure to use === and !== for comparisons. As with many other things in JS, it is only a minefield if you let it become one.

  • OOP: Javascript IS NOT (!==) class based. "Going out of its way" would be adding syntax for traditional class constructs that do not fit in with a prototype based object model. It really is important to approach Javascript with a different mindset than many other popular languages. If you are coming from Lisp you will feel right at home. There is much documentation out there on how to achieve things like private/privileged/static variables/methods in JS. Almost all of this involves Clousers, Functions as first-class objects, and Scope (maybe the three most important keywords in Javascript). Take some time upfront to really understand these aspects of Javascript rather than just copying code. Also experiment, use the console in Firebug to throw together examples of code whose behavior you might find confusing. Once you understand the how and why of advanced Javascript techniques, you will no longer feel like you are "going out of your way" to emulate certain class based OOP techniques. More so, you'll realize that those techniques are not always the best solution and find better methods that take advantage of Javascript's flexibility.

    This page is a good proper introduction to Javascript and its ways: http://www.crockford.com/javascript/javascript.html

  • Sloppy Mindset: Javascript will not force or even nudge you into using good practices. Such are the consequences of a language that is at the same time extremely flexible and extremely lenient. Accept this. Then use tools like jslint to keep your code in check especially in the beginning. In the end the best way to avoid this sloppy mindset is again to understand the language. For instance, many PHP coders coming to Javascript ended up treating it's array's just like PHP's associative arrays. In some cases this bad practice worked without issue, and of course no JS interpreter threw any kind of warning about it. But if you understand the differences between object properties and array indexes in Javascript, you will not likely make this mistake as you will know the potential problems that can result because of it.

    The paradox of Javascript is that by its very nature it invites you to jump right in and start banging out superficially procedural code, while at the same time demanding a fundamental understanding of functional programing and prototype based objects in order to use it properly and harness its full potential.

    Also remember that this understanding is equally essential when using libraries like jQuery.

So in summary, how do you write quality Javascript? By fundamentaly understanding how the language works. This is not hard, though it might be intimidating because it is different. Read about, and experiment with Clousers, Scope, and Functions as objects. Learning Javascript is kind of like learning to drive a stick shift. Once you get it, you'll find you might like it and the high level of control it provides, even if it can be a pain in the ass sometimes.

What practices should you use? Once you understand the language, you will already know.

Tools for debugging? Well that is pretty simple, use Firebug. And when testing for compatibility, use the console that is built in to every major browser, even IE. Also use whatever text editor/IDE you are comfortable with. I like to use Vim, but that's just me.

MooGoo
+1  A: 

I just want to add my two cents. Don't fight it. Javascript is a very nice language, but people (including myself) initially approach it with a "similar to..." vision, and try to force concepts and patterns found in other languages into it.

I used to hate JavaScript, but after a while I improved my skills and learned to appreciate the language for what it is, without trying to coerce an unnatural programming style imported from any foreign language. Don't trust Crockford's "the good parts" as a mantra. His view is, in my opinion, excessive as he tries to force javascript into unnatural, eventually complex designs borrowed from other languages, in particular when it comes to class inheritance and "abuse" of closures to achieve results the language does not provide (such as private vars).

It takes a bit of time, but once you realize how javascript works, it comes out as a language pleasant to learn and use.

Stefano Borini
So how does Javascript work?
donut
@donut : It takes time, and you learn its behavior. learn by practice.
Stefano Borini
The problem I've run into is that I can tell it's not built to work like class based languages but I haven't been able to figure out how to use it in a way where it feels comfortable, like I'm using it how it was "meant" to be used. Guess I'll keep trying.
donut
@donut : I have a post on my blog about this in draft since ages. I guess I should resume working on it, so you can get some insight out of my experience.
Stefano Borini
I would love to read it once you get it out. Please put a comment here if you get around to it.
donut
@donut Give me a couple of weeks. I need to pick javascript up again.
Stefano Borini