Should I use JSLint or JSHint JavaScript validation? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am currently validating my JavaScript against JSLint and making progress on, it's assisting me to write better JavaScript - in particular in working with the Jquery library.
I have now come across JSHint, a fork of JSLint.
So I am wondering for web applications, which are very much JavaScript was driven, which is the better or most applicable validation tool to work against:
JSLint or JSHint?
I want to decide now on a validation mechanism and moving forward, use this for client side validation.
And Difference between jshint and jslint? Please explain in single javascript example.
Links:
jshint- http://www.jshint.com/
jslint- http://jslint.com/

TL;DR
Use JSLint if you're looking for a very high standard for yourself or your team, but bear in mind that it's not necessarily the standard, only a standard, some of which comes to us dogmatically from Doug Crockford.
If you want to be a bit more flexible or have some old pros on your team that don't buy into JSLint's opinions or are going back and forth between JavaScript and other C-family languages regularly, try JSHint.
Full version
Two articles with the reasoning behind the fork explain why JSHint exists:
JSHint: A Community-Driven Fork Of JSLint
Why I forked JSLint to JSHint
The idea behind JSLint is that it's community-driven rather than Crockford-driven. JSHint is generally more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical opinions that JSLint is a stickler for.
For example, if you think both 1. and 2. below are fine, or if you want to write code with one or more of 1.'s aspects that aren't available in 2., JSHint is for you. If you think 2. is the only correct option, use JSLint. I'm sure there are other differences, but this highlights a few.
Passes JSHint out of the box - fails JSLint
(function() {
"use strict";
var x=0, y=2;
function add(val1, val2){
return val1 + val2;
}
var z;
for (var i=0; i<2; i++){
z = add(y, x+i);
}
})();
Passes Both JSHint and JSLint
(function () {
"use strict";
var x = 0, y = 2, i, z;
function add(val1, val2) {
return val1 + val2;
}
for (i = 0; i < 2; i += 1) {
z = add(y, x + i);
}
}());
I find the JSLint code more visually appealing. The only features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0 declarations, and some of the whitespace enforcements for function declarations.
A few of the whitespace things that JSLint enforces are not necessarily bad but are just out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc.) often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches legitimate bugs and very badly formed code, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.
A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is just about pushing one version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.

[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).
When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.
Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.
In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.
With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.
There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)
[ORIGINAL ANSWER FOLLOWS]
By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.
Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.
Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.

There is an another mature and actively developed "player" on the javascript linting front - ESLint:
ESLint is a tool for identifying and reporting on patterns found in
ECMAScript/JavaScript code. In many ways, it is similar to JSLint and
JSHint with a few exceptions:
ESLint uses Esprima for JavaScript parsing.
ESLint uses an AST to evaluate patterns in code.
ESLint is completely pluggable, every
single rule is a plugin and you can add more at runtime.
What really matters here is that it is extendable via custom plugins/rules. There are already multiple plugins written for different purposes. Among others, there are:
eslint-plugin-angular (enforces some of the guidelines from John Papa's Angular Style Guide)
eslint-plugin-jasmine
eslint-plugin-backbone
And, of course, you can use your build tool of choice to run ESLint:
grunt-eslint
gulp-eslint

I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.
Contrary to the answers in this question, my conclusion was not:
By all means use JSLint.
Or:
If you're looking for a very high standard for yourself or team, JSLint.
As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.
So the reasons to choose one over another are more political than technical.
We've finally decided to go with JSHint because of the following reasons:
Seems to be more configurable that JSLint.
Looks definitely more community-driven rather than one-man-show (no matter how cool The Man is).
JSHint matched our code style OOTB better that JSLint.

I'd make a third suggestion, Google Closure Compiler (and also the Closure Linter). You can try it out online here.
The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.
Code Hinting
While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend #ugly_syntax calls:
smaller design space.
This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.
Therefore my current favourite zero-config JS code style:
StandardJS.
UPDATE:
Flow has improved a lot. With it, you
can add types to your JS with will help you prevent a lot
of bugs. But it can also stay out of your way, for instance
when interfacing untyped JS. Give it a try!
Quickstart / TL;DR
Add standard as a dependency to you project
npm install --save standard
Then in package.json, add the following test script:
"scripts": {
"test": "node_modules/.bin/standard && echo put further tests here"
},
For snazzier output while developing, npm install --global snazzy and run it instead of npm test.
Note: Type checking versus Heuristics
My friend when mentioning design space referred to Elm and I encourage you to give that language a try.
Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.
Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.
We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.
Compare Main.elm (typed) ⇔ index.js (untyped, no tests)
(ps. note that the React code is not idiomatic and could be improved)
One final remark,
the reality is that JS is untyped. Who am I to suggest typed programming to you?
See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).
But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.
I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.
Peace.

Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.
Declare all the global var in that file like:
/*global require,dojo,dojoConfig,alert */
Declare all the lint settings like:
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
Hope this will help you :)

There is also an another actively developed alternative - JSCS — JavaScript Code Style:
JSCS is a code style linter for programmatically enforcing your style
guide. You can configure JSCS for your project in detail using over
150 validation rules, including presets from popular style guides like
jQuery, Airbnb, Google, and more.
It comes with multiple presets that you can choose from by simply specifying the preset in the .jscsrc configuration file and customize it - override, enable or disable any rules:
{
"preset": "jquery",
"requireCurlyBraces": null
}
There are also plugins and extensions built for popular editors.
Also see:
Perfect code, zero effort

Related

Why are semicolons omitted in all my source js files?

I'm starting a web project in Aptana and have downloaded bootstrap (v 3.3.7) and jQuery (compressed). When I imported the files into my js folder, all the files came up with a warning sign and the only warnings I can see are that there are missing semicolons everywhere. I think I've read that semicolons aren't necessary in js (although it's best practice to use them), but I've downloaded these files before for class and didn't receive this warning.
Have I done something wrong? Are these files OK to work with?
Are these files OK to work with?
Yes, missing semicolons in most (but not all) places can be corrected by the JavaScript parser using the error-correction procedure* called Automatic Semicolon Insertion, which is built into the language specification. So leaving them out in the places ASI will fix for you is indeed allowed. But it's important to know ASI's rules if you're doing that. (And important to know the rules for ; in any case.) The Bootstrap team knows the rules. (jQuery uses explicit semicolons.)
It sounds like you just have a lint-style warning enabled that you didn't have enabled before that flags up missing semicolons even in places ASI will fix.
You could disable the warning by searching in the options for "lint" or "code style" or "code quality" options, finding the relevant option, and turning it off, but I wouldn't. Instead, I'd look for how to exempt libraries from lint/code style/code quality analysis, since the source of every library you use is unlikely to fit your overall coding style rules.
* According to the language's original creator, Brendan Eich:
ASI is (formally speaking) a syntactic error correction procedure. If you start to code as if it were a universal significant-newline rule, you will get into trouble.
(Amusingly, he also said he wishes he'd made newlines more significant originally, rather than less. But as he said, that ship sailed in 1995...)

React - using TypeScript vs Flow vs?

I'm currently learning React and I think I understand it pretty well. However, there's one thing that's been bothering me regarding development of robust React applications - what tools do developers use for static type checking?
I really like TypeScript. I think it reduces the pain of developing JavaScript applications quite a lot, thanks to type checking and other neat features. Visual Studio Code also offers a really nice code completion. And I know that I can make it work with React by using typings + DenifitelyTyped.
The thing is, there aren't many tutorials about using React + TypeScript. There also doesn't seem to be many articles about developing using this combo. On the other hand, many people seem to be using Flow, which is a project backed by Facebook (and I guess they also use it).
I've managed to find a discussion on Reddit with pros and cons about going the React + TypeScript / React + Flow way. However, to me, it appears to be quite outdated as it is about 10 months old now. I think a lot has changed since then.
I've also found two articles about using React + Flow and React + TypeScript. The author states some issues he's run into when using both of the options and concludes that TypeScript is "the best bet right now" (November 2015), especially because the Flow project has many issues and receives low developer activity from Facebook. He also mentions it doesn't play well with Babel?
So, I guess the question would be: Is it safe to use the React + TypeScript combo, or will I run into some difficulties? What about Flow? Are there some other similar tools I should check out? Which approach would you recommend?
Update September 2017:
Having more than a year of experience with daily use of TypeScript, and playing with Flow for a while, I've came to the following conclusions:
TypeScript is still painful to use to this very day. The problem is that the JavaScript world just moves so fast that TypeScript keeps lagging behind. Thinking about using that fancy new ES7 stage 3 feature? Nope, you can't. Wishing to get type hints for the latest version of some library? Wait a month, or two, maybe more...
Flow has come a long way, it has been improved a lot, it can catch some things that TS can't. Best of all, it finally works on Windows. Also, there's great plugin for VS Code (no idea why it has only 3/5 rating). And it works 100 % with React Native, TypeScript is not even 50 % there yet.
Most of the time, you don't need types at all. All the additional typing is rarely worth it. JS is a dynamically typed language, get over it :)
TL;DR: If you plan to use any type checker, I recommend using Flow.
Update February 2019:
I believe the recommendation above got out of date and is no longer relevant. Three reasons:
React Hooks are here. They make type-checking your code much easier. In most situations, no additional code is needed.
TypeScript's type inference has improved.
TypeScript has much bigger community than Flow. Even yarn, Facebook's package manager, is moving away from Flow, to TypeScript.
So, I think TypeScript is a much more pragmatic choice than Flow in 2019.
As to whether it's even worth using any type checker at all, I'd say it depends on the project size. Small projects probably don't need it.
I'm going to start this answer saying that I have never used Flow, so I can't say much about it. But, we are using React and TypeScript at work and it works great.
We have all the benefits I imagine you already know about, like refactoring, type safety, autocompletion, etc.
Sure, for what I have seen, the Flow syntax is cleaner than TypeScript, but you can add your types using TypeScript incrementally. I think, this is more a matter of taste. Some people prefer to have the code explicitly typed, others prefer to type less and have a stronger type inference.
About, the technologies I'd say TypeScript is a safe bet, Microsoft is pushing the language (there will be a version 2 soon), Angular is using it as well and there are a lot of Angular developers. Even here on SO, the tag TypeScript has more than 4K followers and it's rare to have an unanswered question.
The big issue with TypeScript, at least for us is that from time to time, we decide to use a component or a library that does not have the type definitions, so we have to create them ourselves. But I guess, that's a way to contribute back to the community.
I just asked myself the same question (though not with React) and found the following articles useful in evaluating the two:
http://michalzalecki.com/typescript-vs-flow/ (2016-07-15)
https://blog.wearewizards.io/flow-and-typescript-part-2-typescript (2015-11-20)
https://blog.wearewizards.io/flow-and-typescript-part-1-flow (2015-11-13)
The approach taken by the flow designers feels more functional with better type inference and a better approach for nulls. However, TypeScript has better community support especially with respect to pulling in types for third party libraries via http://definitelytyped.org/ which is important for having types flow through all your code for maximum type safety. TypeScript is created by Microsoft which has a rich history in writing compilers and evolving the technology in favorable directions - notable here is C# and the fact that they are already adding non-null types (2016-07-11): https://blogs.msdn.microsoft.com/typescript/2016/07/11/announcing-typescript-2-0-beta/
TypeScript seems like the safer bet today.
And for those trying TypeScript out in an existing codebase I found the following settings in my tsconfig.json file really helpful in allowing TypeScript to co-exist nicely with JavaScript (allowing transition one file at a time):
{
"compilerOptions": {
"allowJs": true,
"isolatedModules": true,
...
}
}
In my React development, I have quite a complex Babel / Webpack / Flow / Mocha toolchain set up and never had any issues with Flow. Takes some effort to set everything up (Webpack can be daunting at first), but afterwards, it just works. Flow is definitely the way to go as it is a narrower and more focused technology and as such more likely to play well with other tools. In contrast, TypeScript tries to be a lot more than just a type inference / static type checker tool and so it brings additional baggage and assumptions. So React is a specialized tool that does one thing well while TypeScript is effectively a language layered on top of JavaScript. To make sure Microsoft drives its point home, TypeScript files customarily have a different extension as well (.ts instead of .js) because you are now using a different language, got it?
TypeScript uses code generation to spit out JavaScript whereas in Flow the annotations are simply stripped off, there's no code generation as such. In the past, the Microsoft people promoting TypeScript used to make a statement to the effect that code generation is "file-local" (I don't remember the exact terminology used). This was supposed to provide a soothing reassurance that the TypeScript compiler isn't doing anything too magical. At any rate I can't find that statement prominently displayed any more. With Flow you don't need such assurances as you write in plain JavaScript (or whatever ECMA version you've configured Babel for) and the annotations are, like I said, simply stripped.
Not to mention that TypeScript is coming from a company that specializes in unethical and questionable technical practices (I don't rule out that TypeScript may eventually turn out to be the Mother of all Embrace-Extend-Extinguish ploys). Let's not forget that Microsoft did everything in their power to cause Javascript to fail as they (rightly, if belatedly) foresaw what a threat it represented, and still represents, to their crappy operating system and their bloated office suite.
Additionally, Flow's type system was much more powerful last time I bothered to evaluate TypeScript (circa 2015) and it was much easier to apply it incrementally or even sporadically in the sources. For integrating third party libraries I am using flowtyped and it is very rare that I need to complement those found there with my own definitions.
Finally, the fact that Angular uses TypeScript means absolutely nothing as Angular is not really relevant for new projects. React has won hands down, time to move on.
If you want type checks but would prefer to keep plain old javascript (to avoid compiling, or for portability, etc), here's one important distinction between the two (for React or in general):
With Flow the initial setup can run static analysis on vanilla js (it infers many types):
function square(n) {
return n * n; // Error!
}
square("2");
With TypeScript there's a migration effort and only some vanilla js static analysis without it:
noImplicitReturns which prevents you from forgetting to return at the end of a function.
noFallthroughCasesInSwitch which is helpful if you never want to forget a break statement between cases in a switch block.
TypeScript will also warn about unreachable code and labels, which you can disable with allowUnreachableCode and allowUnusedLabels respectively.
More Benefits To Flow
Flow's Comment Types and Error Suppression take support for vanilla js a step further, by allowing you to gradually incorporate type checks through legal js comments that annotate the type or suppress specific checks you might not be ready for yet. Comment types have been a feature request in TypeScript for quite some time, and only recently has there been a PR for it (see previous link).
Downsides To Flow
That said, all of Flow's simplicity does come at the cost of some pretty complex configuration with some annoying caveats, like how it type checks 3rd party libraries, etc. The best advice someone can give about Flow: try to cross-reference anything you read in their documentation as it's outdated and in some cases can be a little misleading.

How to make jslint less verbose

My "IDE" of choice (it's not a real IDE) is Sublime Text 2.
There are nice plugins for this editor. One that I enjoy using a lot is SublimeClang: It parses your C/C++ code as you write it and shows you where errors and warnings are, just like a "real" IDE. This is fantastic because it cuts out the code/compilation cycle so I only ever need to go back to my terminal once I have my code already written because I can see my errors as I am working on the code.
I had hoped that jsLint (there are plugins for integrating this with the editor as well) would help accomplish the same task for me so that I can spot syntax errors before I test my page in the browser. Oftentimes the best way to do this involves uploading the entire file to the server and loading it up in the browser: While this workflow can be heavily streamlined already there is a lot of appeal to being able to locally check the code before uploading.
The problem I have with jslint is that it throws out way too many opinions about esoteric stylistic choices, many of which I do not care for. You want me to put all my declarations together in one line? No thank you, I have all of these comments here next to the variables, I'm keeping those comments!
Are there flags I can provide to jslint so that it will only warn me about syntax errors?
Many people feel the same way you do about JSLint. One result is the alternative JSHint. Many people find its defaults more to their liking. There are Sublime plugins for it too. Two of them are listed at http://www.jshint.com/platforms/.
JSLint does have several options to change its behavior.
It looks like you can define these in the sublime-jslint.sublime-settings file included with the plugin you linked to (in the "jslint_options" section).

Has anyone used Coffeescript for a production application? [closed]

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 11 years ago.
Coffeescript looks pretty cool. Has anyone used it? What are its Pros & Cons?
We've started to use CoffeeScript in our product - a non-public facing website which is basically an app for browsing certain kinds of data.
We use CoffeeScript as a command-line compiler (not on the server, which we'd eventually like to do).
PROS (for us):
It gets rid of a lot of needless clutter in javascript (eg braces, semi-colons, some brackets) to the extent that the code is cleaner & easier to comprehend at-a-glance than javascript
20-30% less lines of code than javascript (to do exactly the same thing)
CoffeeScript not only removes noise but adds keywords, classes, and features like heredocs to make coding cleaner and somewhat more enjoyable
Given the previous points, it is undoubtedly faster to code in CoffeeScript once you learn the ropes
CONS
When using the command-line compiler: to debug, you're looking at different code when solving the problem (javascript) as when writing the fix (coffeescript). However, somewhat unbelievably, our CoffeeScript is so awesome we've never needed to debug it!
Importantly, we can turn back at anytime. Our coffeescript compiler is just producing readable javascript, so if anyone changes their mind or can't figure something out, then we can just drop back to using the javascript that coffeescript produced - and keep coding.
We use coffeescript for all of the javascript in BusyConf. A large portion of BusyConf is a client side application that runs in browers, including support for offline mode.
All of our coffeescript code is fully tested. The tests themselves are written in coffeescript, and use the Qunit framework (which is written in javascript). We also wrote an extension to the Qunit framework that makes the tests nicer. The Qunit extension is written in CoffeeScript. Our application has a mobile version which is written in CoffeeScript, and it uses the Sencha Touch framework (which is written in javascript).
The take away from that is that you can freely intermix javascript dependencies in your application, but all of the code you write (your application code, tests, etc) can (and should!) be coffeescript.
Almost a year later, it's worth posting some updates:
Ruby on Rails 3.1 is incorporating official CoffeeScript support, which means it's going to see far more real-world use. I gave a talk at RailsConf last month, where most of the attendees hadn't heard of CoffeeScript before and—given dhh's strong endorsement—were eager to get into it.
There's a book on CoffeeScript, currently in eBook and soon to be in print from The Pragmatic Bookshelf. It's called CoffeeScript: Accelerated JavaScript Development, and it's by yours truly. It's based on CoffeeScript 1.1.1.
The language has actually changed very little in the six months between 1.0 and 1.1.1; nearly all of the changes qualify as "bugfixes." I had to make very few tweaks to the code in the book for the transition from 1.0.1 to 1.1.1. However, I'm sure the language will see more significant changes in the future.
The most definitive list of CoffeeScript projects is on the CoffeeScript wiki's In the Wild page.
I'd say that most of the production use of CoffeeScript so far is in conjunction with Appcelerator to create iPhone/Android apps. (Wynn Netherland of The Changelog blurbed my book by describing CoffeeScript as "my secret weapon for iOS, Android, and WebOS mobile development"), but there's going to be a lot more use in production Rails apps—and, I hope, elsewhere—in the coming months.
Coffeescript was used in the Ars Technica reader for iPad http://arstechnica.com/apple/news/2010/11/introducing-the-ars-technica-reader-for-ipad.ars
I really love Coffeescript these days. Essentially the entire HotelTonight iPhone application is written in it (using Appcelerator Titanium, which lets you write "native" apps in JavaScript - they are not web apps, say like Phonegap). I chose to use Coffeescript in this case because it makes organizing and maintaining a large amount of JS a lot easier. I also find it simply a lot more pleasurable to write code with Coffeescript (vs. JavaScript). We also use Coffeescript for the JS in our Rails app, but this is incredibly minor/small amount of code in relation to the entire phone app.
The pros mostly have to do with just being a nicer syntax, but also that it standardizes an OO mechanism, and then adds some nice additions (list comprehensions, some scope things, etc.).
The cons are almost zero for me. The primary one is that it's an extra layer to debug. You will need to look at the generated JS (which is VERY readable and nice), and then map that to your Coffeescript code. For us, this hasn't been an issue at all, but YMMV.
In the end, my take is, there is zero risk in terms of using it on a production app, so, don't let that be a blocker. Then, go try it out. Write some code with it, compare that to what you'd write in JS, look at the generated code to see if you are comfy with being able to read that for debugging needs. Also, hang out in the #coffeescript IRC, people are good there. And finally, see how it would integrate with your app, e.g. what's your "build" process (e.g. for Rails, try Barista, for something standalone, just use the included "coffee -w", etc.).
Coffeescript really just makes writing JS easier. You end up with cleaner, more efficient code.
That being said, you still can only do whatever you can do in vanilla JS. Once you use coffeescript enough, it does become a lot easier to write (good) JS.
So if you haven't used JS a ton, I'd suggest learning coffescript instead. You'll get better, cleaner, less buggy code. If you're already really fluent in JS, it might not be a good idea to start using coffeescript on a "real" app.
(Also, coffeescript does irk me a bit in that it seems to encourage rather "floofy" code. I don't know if it's a good thing or a bad thing, but it seems an extreme case of TMTOWTDI)
Note that although there is a compiler, you don't get static checking due to JavaScript's dynamic nature. As written in the FAQ:
Static Analysis
CoffeeScript uses a straight source-to-source compiler. No type
checking is performed, and we can't work out if a variable even exists
or not. This means that we can't implement features that other
languages can build in natively without costly runtime checks. As a
result, any feature which relies on this kind of analysis won't be
considered.
IDE support is less mature than that of JavaScript (Cloud9 has syntax highlight support, but Eclipse JSDT has refactorings and more): https://stackoverflow.com/questions/4084167/ide-or-its-add-in-for-coffescript-programming

Should I use the YUI Compressor or the new Google Closure compiler to compress my JavaScript?

YUI Compressor was the consensus best tool for minimizing, but Closure seems like it could be better.
"Whichever you find best for you" I think is the general answer at the moment - YUI has been available longer so undoubtedly will be the one which currently has the consensus as being the best tool. Whereas Closure is new to us - so there isn't the wealth of experience with Closure as there is with YUI. Hence I don't think you'd find a compelling real-world arguments of why to use Closure based on people's experiences with it simply because it's new.
That's not to say you shouldn't use Closure....just my round about way of saying, I don't think there's an answer available to this until a number of people have used the 2 and compared them.
Edit:
There are a couple of early comparisons, saying Closure does give an improvement:
http://blog.feedly.com/2009/11/06/google-closure-vs-yui-min/
http://news.ycombinator.com/item?id=924426
Further Edit:
Worth keeping an eye on issue list for Closure: http://code.google.com/p/closure-compiler/issues/list
From the comparisons I've seen, Closure seems to be the clear winner in terms of minimizing file size. This article uses three popular JS libraries (jQuery, Prototype, MooTools) to compare compression between YUI Compressor and Closure Compiler:
http://www.bloggingdeveloper.com/post/Closure-Compiler-vs-YUI-Compressor-Comparing-the-Javascript-Compression-Tools.aspx
Closure comes out in front in each test, particularly in its advanced mode, where it "minimizes code size about 20-25% more than YUI Compressor by providing nearly 60% compression."
Closure can be used in the Simple mode or the Advanced mode. Simple mode is fairly safe for most JavaScript code, as it only renames local variables in functions to get further compression.
Advanced mode is much more aggressive. It will rename keys in object literals, and inline function calls if it can determine that they return simple values with no side effects.
For example:
function Foo()
{
return "hello";
}
alert(Foo());
is translated to:
alert("hello");
And this code:
var o = {First: "Mike", Last: "Koss"};
alert(o);
is translated to:
alert({a:"Mike",b:"Koss"});
You can prevent the Advanced mode from changing key values in object literals by quoting the names like this:
{'First': "Mike", 'Last': "Koss"}
You can try out these and other examples at google's interactive Closure Compiler site.
Looks like jQuery 1.5 just moved to UglifyJS:
Additionally with this switch we’ve
moved to using UglifyJS from the
Google Closure Compiler. We’ve seen
some solid file size improvements
while using it so we’re quite pleased
with the switch.
I think it depends on your code. If you want to compile your own code, then I think it is worth it to patch the code so that it works with Closure Compiler (some things might seem a bit awkward at the start). I believe Closure Compiler soon will be the top choice for such jobs and it will also make you to tidy up your code a bit and maintain consistent style (of course it depends on your preferences, you might hate some parts, I do :P ).
If you depend on other libraries then in my opinion you should wait a bit until they release Closure Compiler compatible versions. It shouldn't take much time for most popular libraries out there. And maybe you can provide fixes for those "not-so-active" libraries which you use yourself.
I'm talking about Advanced Compilation mode here, the Simple Compilation mode as some has pointed out is fairly safe to use.
And here's a different opinion - Google Closure ? I'm Not Impressed. It's maybe a little bit too harsh, but nice read. I guess only time will tell which one is better =)
As of october 2012, looks like YUI compressor is now deprecated, or at least no longer going to be used in YUI: http://www.yuiblog.com/blog/2012/10/16/state-of-yui-compressor/
You can make some tests here, and see what is better in each browser:
http://jsperf.com/closure-vs-yui

Categories