Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have programmed pretty much exclusively in compiled languages, particularly Java, for most of my career. One of my favourite things about Java is how productive you can be, and how little code you actually have to write, when using tools like Eclipse.

You can:

  • Easily and automatically refactor your methods and classes
  • View instantly all the places where a method is invoked, or a constant is used (Open Call Hierarchy/Show References)
  • Static typing means you can use code completion to show all the parameters/functions available on an object
  • Control-click on a function/member/class name to go straight to its definition

All these facilities make me feel like the IDE is my best friend. Writing Java code and particularly understanding other peoples' programs becomes far easier.

However, I am being called on more and more to use Javascript, and my experience so far has been quite negative.

In particular:

  • No immediate way of finding a function's entry point (other than a plain text search, which may then result in a subsequent searches for methods further up the call hierarchy, after two or three of which you've forgotten where you started)

  • Parameters are passed in to functions, with no way of knowing what properties and functions are available on that parameter (other than actually running the program, navigating to the point at which the function is called, and using console.logs to output all the properties available)

  • Common usage of anonymous functions as callbacks, which frequently leads to a spaghetti of confusing code paths, that you can't navigate around quickly.

  • And sure, JSLint catches some errors before runtime, but even that's not as handy as having red wavy lines under your code directly in the browser.

The upshot is that you pretty much need to have the entire program in your head at all times. This massively increases the cognitive load for writing complex programs. And all this extra stuff to worry about leaves less room in my brain for actual creativity and problem solving.

Sure, it's faster to just throw an object together rather than write an entire formal class definition. But while programs may be slightly easier and quicker to write, in my experience they are far harder to read and debug.

My question is, how do other programmers cope with these issues? Javascript is clearly growing in popularity, and the blogs I read are about how productive people are being with it, rather than desperately trying to find solutions to these issues.

GWT allows you to write code for a Javascript environment in Java instead, but doesn't seem to be as widely used as I would expect; people actually seem to prefer Javascript for complex programs.

What am I missing?

share|improve this question
7  
My advice to all Java devs having a hard time with JS is to learn another language that doesn't have a C-based syntax. It will help you get past the syntax-similarity when you come back to JS and it might help you start looking at stuff in terms of tradeoffs of language design rather than seeing things in terms of the one true way to write all code and the way everybody else gets it wrong. And if you get the idea to write a UI framework, please learn JavaScript before saddling us with yet another bloated class-cascading piece of garbage that's inexplicably easy to market to clueless CTOs. –  Erik Reppen Sep 30 '11 at 23:38
4  
Man what a snob me 2 years ago was. I'll try to be a little more helpful now that I've hit the Java harder recently. IDE? Check out Jetbrains Webstorm (I still use Scite primarily but WS ain't bad), but for client-side web, Chrome's dev tools do a pretty good job of covering you on debug and it does actually perform auto-completes when writing snippets of code in the console. Also, spend a lot of time thinking about OOP. IMO, non-optional classes and IDEs as a substitute for human legibility have absolutely murdered the whole point of OOP in a lot of Java out there. –  Erik Reppen May 2 '13 at 17:32
2  
I feel your pain. Dropping down into javascript is the web version of dropping down into assembly language on the client side. It can certainly be fun, but the toolsets are weak and productivity definitely drops with all the extra work you have to do. That's life in programming though. Not everything gets to be done at the highest level of abstraction. :-) –  Brian Knoblauch May 2 '13 at 19:43
1  
@ErikReppen I started as a Java developer but I am fluent in Obj-C, programmed in Ruby, Delphi, C++, C#, Prolog, PHP, bash and I still find javascript the worst to read and mantain. –  Sulthan May 5 '13 at 12:53
1  
Take a look at TypeScript. Once I've start using it I find client-side coding a lot more productive and enjoyable. Hard to beat proper intellisense and early compiler warnings. –  Eugene May 5 '13 at 15:56

9 Answers 9

up vote 21 down vote accepted

The IDE-based niceties are not available* in a dynamic language such as javascript. You have to learn to do without them. You'll have to replace tool support with better design.

Use a module pattern -- either by hand, or with a tool like requirejs. Keep the modules small, so that you can reason about them easily.

Don't define as many types -- use anonymous objects created close to the point of call. Then you can look at the caller and the callee and know what's going on.

Try to avoid coupling your code to the DOM -- Try hard to limit the amount of DOM manipulation you do in your code. If you can pass in selectors or jQuery collections, do that rather than having your code know about the page structure.

*If you're using a popular library, you can get fake autocomplete, but it's more like "show all jquery methods" than like "what properties does this object have". It saves typing, but offers no guarantee of correctness.

share|improve this answer
    
Accepting this one for constructive advice on how to deal with lack of tooling. –  funkybro Sep 28 '11 at 14:35
3  
"You have to learn to do without them." OR scrap it OR use higher-level language that generates javascript and has proper tools. –  Den Jul 17 '12 at 17:14
    
@Den: Do you have a suggestion for a higher-level language with advanced tools? In my experience, advanced tools are made for popular languages. What higher-level language that compiles into javascript is popular enough to have such tools? –  Sean McMillan Jul 18 '12 at 16:32
1  
@SeanMcMillan: some .NET(C#/F#) examples are jsil.org, projects.nikhilk.net/ScriptSharp, sharpkit.net, websharper.com –  Den Jul 19 '12 at 8:28
1  
@SeanMcMillan Java also, see GWT developers.google.com/web-toolkit –  funkybro Aug 8 '12 at 9:17

I used to dislike javascript (and its dynamic typing) but I have grown to appreciate its object orientation, closures and functional programming. Also, its global objects and removal of silent type conversion were a breath of fresh air when I first found them.

My preferred ide for javascript is webstorm as it is easy to get jQuery intellitext working (shame its not free).

Also, I wouldn't say its growing - its ubiquitous already.

Your specific points:

No immediate way of finding a function's entry point

I don't understand this, how could it be any simpler ?

Parameters are passed in to functions, with no way of knowing what properties and functions are available on that parameter

If you set up your ide to include the objects definition the properties of the object will be available via intellitext (but i may have missed your point here).

Common usage of anonymous functions as callbacks, which frequently leads to a spaghetti of confusing code paths, that you can't navigate around quickly.

Common usage ? If you don't like anonymous functions, don't use them. Or are you referring to jQuery which uses them substantially ? jQuery is probably regarded by most web developers as the single biggest time saver in the history of web development.

JSLint catches some errors before runtime

It catches all of them, you can include it into your ide. Or Webstorm includes it by default (i think).

share|improve this answer
    
To be fair ubiquitous and popular aren't necessarily the same! ;-) Anyway, webstorm is an excellent IDE for JavaScript (and though not free it's pretty cheap). I've not used it but I believe IntelliJ (also from Jetbrains) contains the same functionality which might be relevant if you're from a Java background and want to use a single IDE. –  FinnNk Sep 27 '11 at 8:36
    
OK maybe I need to clarify... I meant "growing in popularity" more in the context of development outwith the browser/DOM. I.e., it gets used where other alternatives are available. By "function's entry point" I meant locating the point in the code at which a function is invoked. Parameter properties: there is no way for an IDE to know the properties of a given object before runtime! Anonymous functions: I may not like them, but others whose code I need to maintain do. JSLint does not know whether I have mistyped a property name of a given object, for instance. –  funkybro Sep 27 '11 at 8:57
    
@funkybro "there is no way for an IDE to know the properties of a given object before runtime" There is, just include "whateverMyObjectIs.js" as a referenced script in the ide, and for mistyped property names, try webstorm it does this (if I remember correctly). –  NimChimpsky Sep 27 '11 at 9:04
3  
There is not! Consider this code: var myFunc = function(param) { ... }; var myObj1 = { fooProp: fooVal, barProp: barVal}; var myObj2 = { catProp: catVal, dogProp: dogVal}; myFunc(myObj1); myFunc(myObj2); How can an IDE offer code completion on myFunc's param parameter? param could be any object of any type, with any properties. –  funkybro Sep 27 '11 at 9:09
    
Yes, but presumably the params you're passing in are actually available in that context. A parser can sort that out without being its own full blown JS interpreter. –  Erik Reppen Sep 30 '11 at 23:16

If you like IDEs and are used to eclipse check out Aptana as an IDE For JavaScript. I think it can do much of what you want. (I personally hate IDEs but that is a different conversation).

As for anonymous functions, I find that they are the most powerful feature in JavaScript and trying to work in a language that does not have them is at this point quite painful.

If you want something else that can compile to JavaScript there are a bunch of options, CofffeeScript, Clojure and GWT all jump to mind but there are others.

share|improve this answer
2  
I tried Aptana once, and it's really bad. It doesn't even have auto-indentation and it destroys all project settings set by other Eclipse editors e.g. coloring and stuff if I use Eclipse and Aptana in the same project. –  Jonas Sep 27 '11 at 10:41
1  
I used it for a while and hated it, but as I said I hate IDE's I do formatting by command line tool and edit in GVIM or emacs (depending on what I am doing) –  Zachary K Sep 27 '11 at 11:03
    
Crashes in the first few hours and I have nothing open other than a handful of files? Buh-bye. –  Erik Reppen Sep 30 '11 at 22:58
    
Webstorm ain't bad. I still use Scite most of the time but I'm starting to feel the IDE thing more when writing Node.js stuff and I don't have the benefit of visible browser feedback and dev tools. –  Erik Reppen May 2 '13 at 17:34

That's the price we pay for using poorly typed languages. One can only wonder why this abomination has become so popular. The disadvantages far outweigh the advantages of poorly typed languages.

Perhaps we should apply the Non-cooperation-principle to this junk to make it go away.

share|improve this answer
3  
"poorly typed languages" -- Many programmers would disagree with you. –  Sean McMillan Sep 27 '11 at 12:56
6  
+1, The only reason Javascript is popular is because it was in the right place at the right time. –  maple_shaft Sep 27 '11 at 13:03
2  
Aw, you guys are just sad that Node.js has bindings to C++ instead of Java aren't you? –  Erik Reppen Sep 30 '11 at 22:57
1  
I'm not sure what is meant by "poorly typed languages". JavaScript is not "poorly typed". It's dynamically typed, and operations may cause type coercion. Don't blame the language because your editor/IDE doesn't know the type of the variable - you should know it anyway. –  Ryan Kinal Jul 17 '12 at 14:58
3  
@RyanKinal Really? You should know all properties and methods of all objects and classes within your entire app, and of your language's API, and that of any libraries you're using, by memory? You reject the notion of IDE code-completion massively improving productivity by reducing the cognitive load and giving you less stuff to think about? –  funkybro Jul 18 '12 at 8:33

What you're saying is just the common gripe of a Java minded person looking at JavaScript.

Let's first answer your question...

... my question is, how do other programmers cope with these issues ...

Answer: They DON'T. They learn the JavaScript philosophy by first relinquishing the Java cult.

You have to understand this premise... JavaScript is NOT Java. It's just not about syntax -- it's more about the philosophy.

Now let's take up some of them...

  • View instantly all the places where a method is invoked, or a constant is used (Open Call Hierarchy/Show References)

    Control-click on a function/member/class name to go straight to its definition

    All of these are available -- just pick a decent IDE.

  • Static typing means you can use code completion to show all the parameters/functions available on an object

    This is not a problem you cope with. This is something that requires changing your outlook on programming. Loose type system is one of the strengths of JavaScript. Understand loose typing -- and learn to appreciate it. Besides, code completion works very well with JS.

  • And sure, JSLint catches some errors before runtime, but even that's not as handy as having red wavy lines under your code directly in the browser.

    Firebug, Chrome/Safari console and even IDEs do all that and MORE.

    There is JSHint that can do the nifty static analysis that Java programmers are used to.

  • The upshot is that you pretty much need to have the entire program in your head at all times. This massively increases the cognitive load for writing complex programs.

    Wrong! On the contrary, JavaScript is a "lightweight" programming language -- and encourages you to have simpler programs. As Doug Crockford says ... it will "punish" you if you tried to write heavily model based programs in JavaScript.

  • while programs may be slightly easier and quicker to write, in my experience they are far harder to read and debug.

    Totally wrong! How do you decide readability based on programming language? Programs are readable (or not) -- NOT languages. Plus, JavaScript's got fantastic debuggers.

Pardon me if I sounded a little rude -- but the truth is you have to change your Java disposition to understand JavaScript.

Only "mature" Java programmers can appreciate JavaScript -- and you can't master that which you don't appreciate. Again, sorry for being outright blunt.

share|improve this answer
2  
Do you have an exmple of a JavaScript IDE where I can "control-click on a function/member/class name to go straight to its definition"? I use Eclipse for Java and Scala but lack a good IDE/Editor for JavaScript. –  Jonas Sep 27 '11 at 9:25
11  
Prepared to take some criticism, but some things in here are quite wrong. If I create an object, and then pass it into a function, I can ctrl-click on the parameter and view its properties? No I can't, because the object could be anything. If I misspell one of the object property names, will it warn me? No it won't, because it's not an error in JS, even though it's probably never what you want. Helpful code completion is impossible. Finding out what properties a function's parameter possesses involves spelunking through the code invoked the function, to find out where the object was created. –  funkybro Sep 27 '11 at 10:27
3  
You can complain that the way JS is built makes it harder for IDEs to code for you. I would complain that in Java I can't just stick dynamic properties to damn near anything I want or do introspection on objects all during run-time. The two languages are very different in philosophy. I think in ways that create a larger disconnect between Java and JS devs than between JS and most other languages. I personally find C easier to adapt to than Java and I detest working with a bloated IDE. –  Erik Reppen Sep 30 '11 at 22:46
2  
Even Google's Java devs can't seem to get their heads out of Java when writing JS. sitepoint.com/google-closure-how-not-to-write-javascript –  Erik Reppen Sep 30 '11 at 23:01
3  
You write: JavaScript is NOT Java and you have to change your Java disposition to understand JavaScript followed by: Only "mature" Java programmers can appreciate JavaScript... So in order to understand Javascript I must first master Java, and then forget all about it? –  Caleb May 2 '13 at 16:11

What am I missing?

You are missing the two enormous advantages that Javascript has over Java:

  • Javascript code is about one-fourth the size of equivalent Java code.
  • You never have to wait for a compile and server restart.

I work differently in Javascript. I add a little bit of code at a time, as little as I can possibly test, and refresh the browser and test it. With jQuery, a couple lines of Javascript are all I need most of the time.

I have found Java programming to be relatively unproductive, and am now writing all my server-side code in Groovy, for the same two reasons.

share|improve this answer
4  
"Javascript code is about one-fourth the size of equivalent Java code" <-- this is the problem! Sure it's fast to just create anonymous functions and add extra properties to objects, and throw them around like confetti. But what about when someone else visits your code and tries to figure out what is going on? Besides, more code in Java does not necessarily equal more typing... Eclipse writes so much of it for you. –  funkybro Sep 27 '11 at 13:28
3  
@funkybro: Eclipse writes it... then I am stuck looking past it for the life of the project. If it's required, but a trivial plugin can generate it, that's a language smell. You are right that Javascript classes require a bit more documentation. But just knowing a Java method signature isn't sufficient either. –  kevin cline Sep 27 '11 at 14:18
1  
It's not required! You could simulate Javascript in Java by always invoking methods with reflection, and using nothing but plain objects, lists and maps if you really wanted to. However most developers IME (not all I confess!) choose to define meaningful data types, as they find it helps them write maintainable, self-documenting code! –  funkybro Sep 27 '11 at 15:12
1  
Does reflection allow Java to modify objects during run-time? How about closures? Learn the language before you criticize it or assume Java, the most closed-paradigm language outside of assembly is capable of emulating it. –  Erik Reppen Sep 30 '11 at 22:55
1  
Downvoters: this is not a referendum on Java vs. Javascript. It's rude to downvote without a reason. –  kevin cline Jul 17 '12 at 14:41

I haven't used it yet myself but I've seen some demos and I'm very impressed with Cloud 9 as a JavaScript IDE.

You can go for both the online service model or download it off GitHub.

And as evidence of its quality as an IDE, Cloud9 was written using... Cloud9!

share|improve this answer

In general, it is hard to have tools you mentioned for a dynamic language (unless the IDE is a part of the runtime - i.e. Smalltalk). Having said that, once you learn a really good text editor, most IDEs look less attractive - that's at least my experience.

share|improve this answer

I'd like to add an answer to this question as I've been trudging through some good, bad but mostly ugly Java lately and I have a whole new whopper-load of gross over-generalizations about Java and Java devs vs. JS and JS devs that might actually be based in something vaguely resembling useful truth.

There Are IDEs But It Can Be Helpful to Understand Why There Haven't Been Many

I've been trying Webstorm out now that I find myself drawn to Node development and it's not-bad-enough that I actually bought it but I still tend to open js files in Scite more often than WS. The reason for this is that you can do a lot more with a lot less in JS but also because UI work gives immediate feedback, browser dev tools (Chrome's and Firebug in particular) are actually quite excellent, and (accounting for non-browser contexts) re-running altered code is fast and easy without a compile step.

Another thing I'm fairly convinced of is that IDEs basically create their own demand by enabling sloppy code which you really can't afford in JavaScript. Want to learn how we manage in JS? It might help to start by trying to write something non-trivial in Java without an IDE and pay close attention to the things that you have to start doing and think about in order to actually be able to maintain/modify that code without an IDE moving forward. IMO, those same things are still critical to writing maintainable code whether you have an IDE or not. If I had to write a 4-year programming curriculum, it wouldn't let you touch an IDE for the first two years in the interest of not getting tools and dependencies twisted.

Structure

Experienced JS devs dealing with complex applications can and do structure their code. In fact it's one thing we tend to have to be better at with an early history that lacked IDEs to read the code for us but also because powerfully expressive languages can powerfully express completely unmaintainable disaster codebases very quickly if you don't code thoughtfully.

I actually had a fairly steep learning curve in understanding our Java codebase recently until I finally realized that none of it was proper OOP. Classes were nothing more than bundles of loosely related methods altering globally available data sitting around in beans or DTOs or static getters/setters. That's basically the same old beast that OOP was supposed to replace. So I stopped looking and thinking about the code basically. I just learned the shortcut keys and traced through the messes and everything went much more smoothly. So if you're not in the habit already, think a lot harder about OOD.

A well-structured JS app at the highest level will tend to consist of complex functions (e.g. jQuery) and objects interacting with each other. I would argue that the mark of a well-structured, easily maintained app in any language is that it's perfectly legible whether you're looking at it with an IDE or Notepad++. It's one of the main reasons I'm highly critical of dependency injection and test-first TDD taken to the extreme.

And finally, let go of classes. Learn prototypal inheritance. It's actually quite elegant easy to implement when you actually need inheritance. I find compositing approaches tend to work much better in JS, however, and I personally start to get ill and have EXTJS night-terrors any time I see more than one or two levels of inheritance going on in any language.

Core Principles First

I'm talking about the core stuff that all other good practices should derive from: DRY, YAGNI, the principle of least astonishment, clean separation of problem domains, writing to an interface, and writing human legible code are my personal core. Anything a little more complex that advocates the abandonment of those practices should be considered Kool Aid in any language, but especially a language like JavaScript where it's powerfully easy to leave a legacy of very confusing code for the next guy. Loose coupling, for instance, is great stuff until you take it so far that you can't even tell where interaction between objects is happening.

Don't Fear Dynamic Typing

There aren't a lot of core types in JavaScript. For the most part, dynamic casting rules are practical and straight-forward but it pays to learn them so you can better learn to manage data flow without needless casts and pointless validation routines. Trust me. Strict types are great for performance and spotting problems on compile but they don't protect you from anything.

Learn the Crap out of JS Functions and Closures

JS's first-class functions are arguably the main reason JS won the "Only Language Worth Touching the Client-Side Web With Award." And yes, there actually was competition. They're also a central feature of JS. We construct objects with them. Everything is scoped to functions. And they have handy features. We can examine params via the arguments keyword. We can temporarily attach and fire them in the context of being methods of other objects. And they make event-driven approaches to things obscenely easy to implement. In short, they made JS an absolute beast at reducing complexity and adapting varying implementations of JS itself (but mostly the DOM API) right at the source.

Re-Evaluate Patterns/Practices Before Adopting

First class functions and dynamic types render a lot of the more complex design patterns completely pointless and cumbersome in JS. Some of the simpler patterns, however, are incredibly useful and easy to implement given JS's highly flexible nature. Adapters and decorators are particularly useful and I've found singletons helpful for complex ui widget factories that also act as event-managers for the ui elements they build.

Follow the Language's Lead and Do More With Less

I believe one of the Java head honchos makes the argument somewhere that verbosity is actually a positive feature that makes code easier to understand for all parties. Hogwash. If that were true, legalese would be easier to read. Only the writer can make what they've written easier to understand and you can only do that by putting yourself in the other guy's shoes occasionally. So embrace these two rules. 1. Be as direct and clear as possible. 2. Get to the damn point already. The win is that clean, concise code is orders of magnitude easier to understand and maintain than something where you have to traverse twenty-five layers to get from the trigger to the actual desired action. Most patterns that advocate that sort of thing in stricter languages are in fact workarounds for limitations that JavaScript doesn't have.

Everything is Malleable and That's Okay

JS is probably one of the least protectionist languages in popular use. Embrace that. It works fine. For instance you can write objects with inaccessible persistent "private" vars by simply declaring regular vars in a constructor function and I do this frequently. But it's not to protect my code or users of it "from themselves" (they could just replace it with their own version during run-time anyway). But rather it's to signal intent because the assumption is that the other guy is competent enough to not want to mangle any dependencies and will see that you're not meant to get at it directly perhaps for a good reason.

There Are No Size Limits, Only Problem Domains

The biggest problem I have with all the Java codebases I've seen is an overabundance of class files. First of all SOLID is just a confusing reiteration of what you should already know about OOP. A class should handle a specific set of related problems. Not one problem with one method. That's just taking bad old chaining func-spaghetti C code only with the addition of all the pointless class syntax to boot. There is no size or method limit. If it makes sense to add something to an already long function or class or constructor, it makes sense. Take jQuery. It's an entire library-length toolset in a single function and there is nothing wrong with that. Whether we still need jQuery is up to reasonable debate but in terms of design, you can learn a hell of a lot about how to write effective JavaScript by understanding how JQ is architected for minimal memory usage/performance impact through slick use of closures and the prototype property.

If Java is All You Know, Dabble in Something With a Non-C-Based Syntax

When I started messing with Python because I liked what I was hearing about Django, I learned to start separating syntax from language design. As a result, it became easier to understand Java and C as a sum of their language design parts rather than a sum of things they do differently with the same syntax. A nice side-effect is that the more you understand other languages in terms of design, the better you'll understand the strengths/weaknesses of the one you know best through contrast.

Conclusion

Now, considering all of that, lets hit all your problem-points:

  • No immediate way of finding a function's entry point (other than a plain text search, which may then result in a subsequent searches for methods further up the call hierarchy, after two or three of which you've forgotten where you started)

Chrome and Firebug do actually have call-tracing. But see also my points on structure and keeping things concise and direct. The more you can think of your app as larger well-encapsulated constructs interacting with each other, the easier it is to figure whose fault it is when things go wrong. I'd say this is true of Java too. We have class-like function constructors that are perfectly serviceable for traditional OOP concerns.

function ObjectConstructor(){
    //No need for an init method.
    //Just pass in params and do stuff inside for instantiation behavior

    var privateAndPersistent = true;

    //I like to take advantage of function hoisting for a nice concise interface listing
    this.publicAndPointlessEncapsulationMurderingGetterSetter
    = publicAndPointlessEncapsulationMurderingGetterSetter;
    //Seriously though Java/C# folks, stop with the pointless getter/setters already

    function publicAndPointlessEncapsulationMurderingGetterSetter(arg){
        if(arg === undefined){
            return privateAndPersistent;
        }
        privateAndPersistent = arg;
    }

}

ObjectConstructor.staticLikeNonInstanceProperty = true;

var instance = new ObjectConstructor();//Convention is to  capitalize constructors

In my code, I almost never use the object literals {} as structural app components since they can't have internal (private) vars and prefer instead to reserve them for use as data structures. That helps set an expectation that maintains clarity of intent. (if you see curlies, it's data, not a component of app architecture).

  • Parameters are passed in to functions, with no way of knowing what properties and functions are available on that parameter (other than actually running the program, navigating to the point at which the function is called, and using console.logs to output all the properties available)

Again, see modern browser tools. But also, why is it such a bummer to run the program again? Reload is something a client-side web dev typically hits every few minutes because it costs you absolutely nothing to do it. This is again, another point that app structure can be helpful with but it is one down-side tradeoff of JS that you have to run your own validation when enforcing contracts is critical (something I only do at endpoints exposed to other things my codebase doesn't control). IMO, the tradeoff is well worth the benefits.

  • Common usage of anonymous functions as callbacks, which frequently leads to a spaghetti of confusing code paths, that you can't navigate around quickly.

Yeah that's bad on anything non-trivial. Don't do that. Name your functions kids. It's easier to trace things as well. You can define, evaluate (required to assign), and assign a simple trivial function in-line with:

doSomethingWithCallback( (function callBack(){}) );

Now Chrome will have a name for you when you're tracing through calls. For non-trivial func I would define it outside of the call. Also note that anonoymous functions assigned to a variable are still anonymous.

  • And sure, JSLint catches some errors before runtime, but even that's not as handy as having red wavy lines under your code directly in the browser.

I never touch the stuff. Crockford's given some good things to the community but JSLint crosses the line into stylistic preferences and suggesting certain elements of JavaScript are bad parts for no particularly good reason, IMO. Definitely ignore that one thing about regEx and negation classes followed by * or +. Wildcards perform more poorly and you can easily limit the repetition with {}. Also, ignore anything he says about function constructors. You can easily wrap them in a factory func if the new keyword bothers you. CSSLint (not Crockford's) is even worse on the bad advice front. Always take people who do a lot of speaking engagements with a grain of salt. Sometimes I swear they're just looking to establish authority or generate new material.

And again, you must unlearn what you have learned with this run-time concern you have. (it's a common one I've seen with a lot of Java/C# devs) If seeing errors in run-time still bothers you 2 years later, I want you to sit down and spam reload in a browser until it sinks in. There is no compile-time/run-time divide (well not a visible one anyway - JS is run on a JIT now). It's not only okay to discover bugs at run-time, it's hugely beneficial to so cheaply and easily spam reload and discover bugs at every stopping point you get to.

And get crackin' on those Chrome dev tools. They're built-in directly to webkit. Right-click in Chrome. Inspect element. Explore the tabs. Plenty of debug power there with the ability to alter code in the console during run-time being one of the most powerful but less obvious options. Great for testing too.

On a related note, errors are your friends. Don't ever write an empty catch statement. In JS we don't hide or bury errors (or at least we shouldn't cough YUI /cough). We attend to them. Anything less will result in debug pain. And if you do write a catch statement to hide potential errors in production at least silently log the error and document how to access the log.

share|improve this answer
2  
Upvoting for the size of the answer... –  Florian Margaine May 5 '13 at 19:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.