Seattle, WA, US. Engineering Manager, Web Platform. Business Intelligence Engineer. Toronto, ON ,CA. Android Engineer.
See jobs for CoffeeScript. See jobs for jQuery. What companies use CoffeeScript? What companies use jQuery? See which teams inside your own company are using CoffeeScript or jQuery. Sign up to get full access to all the companies Make informed product decisions. What tools integrate with CoffeeScript? What tools integrate with jQuery? Sign up to get full access to all the tool integrations Make informed product decisions.
What are some alternatives to CoffeeScript and jQuery? JavaScript is most known as the scripting language for Web pages, but used in many non-browser environments as well such as node. When the range has two dots it will be inclusive, meaning the range will contain the specified start and end element. If it has three dots … , it will only contain the numbers in between. List comprehensions were one of the biggest new concepts to grasp when I started learning CoffeeScript.
They are an extremely powerful feature, but it does take some time to get used to and think in comprehensions. Whenever you feel tempted to write a looping construct using the lower level while , consider using a comprehension instead. They provide just about everything you could possibly need when working with collections, and they are extremely fast compared to built-in ECMAScript array methods, such as. You can use comprehensions to loop through key-value pairs in an object, using the of keyword, as shown in the following code:.
CoffeeScript introduces some very nice logic and conditional features, some also borrowed from other scripting languages. The unless keyword is the inverse of the if keyword; if and unless can take the postfix form, meaning statements can go at the end of the line. CoffeeScript also provides plain English aliases for some of the logical operators.
CoffeeScript allows you to easily extract parts of an array using the.. Both [.. These are used in the following code:. CoffeeScript sure loves its ellipses. They are used by splats, ranges, and array slices.
Here are some quick tips on how to identify them: If the … is next to the last argument in a function definition or a function call, it's a splat. If it's enclosed in square brackets that are not indexing an array, it's a range. If it is indexing an array, it's a slice. Destructuring is a powerful concept that you'll find in many functional programming languages.
In essence, it allows you to pull single values from complex objects. It can simply allow you to assign multiple values at once, or deal with functions that return multiple values; as shown here:. When you run this, you get three variables, city , state , and country with values that were assigned from the corresponding element in the array returned by the getLocation function.
You can use destructuring to pull out values from objects and hashes as well. There are no limits to how deeply data in the object can be nested. Here is an example of that:.
When we put the myStreet variable inside our pattern, we tell CoffeeScript to assign the value in that place to myStreet. While we can use nested objects, we can also mix and match destructuring objects and arrays, as shown in the following code:. Here, in the previous code, we are pulling elements from the array value that we get from addressLines and give them names. In JavaScript, the value of this refers to the owner of the currently executing function, or the object that the function is a method of.
Unlike in other object-oriented languages, JavaScript also has the notion that functions are not tightly bound to objects, meaning that the value of this can be changed at will or accidently. This is a very powerful feature of the language but can also lead to confusion if used incorrectly. In CoffeeScript, the symbol is a shortcut for this. Whenever the compiler sees something like foo , it will replace it with this. Although it's still possible to use this in CoffeeScript, it's generally frowned upon and more idiomatic to use instead.
In any JavaScript function, the value of this is the object that the function is attached to. However, when you pass functions to other functions or reattach a function to another object, the value of this will change. Sometimes this is what you want, but often you would like to keep the original value of this. This is especially useful when using callbacks, for instance in a jQuery event handler. Notice that the prepare function on the birthday class takes an action function as an argument, to be called when the birthday occurs.
Because we're passing this function using the fat arrow, it will have its scope fixed to the Person object. This means we can still refer to the name instance variable even though it doesn't exist on the Birthday object that runs the function.
In CoffeeScript, switch statements take a different form, and look a lot less like JavaScript's Java-inspired syntax, and a lot more like Ruby's case statement. You don't need to call break to avoid falling through to the next case condition. CoffeeScript doesn't force you to add a default else clause, although it is a good programming practice to always add one, just in case.
CoffeeScript borrowed chained comparisons from Python. These basically allow you to write greater than or less than comparisons like you would in mathematics, as shown here:. Most programming books start with comments, and I thought I would end with them. In CoffeeScript, single line comments start with. The comments do not end up in your generated output. Multiline comments start and end with , and they are included in the generated JavaScript. You can span a string over multiple lines using the """ triple quote to enclose it.
In this chapter, we started looking at CoffeeScript from JavaScript's perspective. We saw how it can help you write shorter, cleaner, and more elegant code than you normally would in JavaScript and avoid many of its pitfalls. We came to realize that even though CoffeeScripts' syntax seems to be quite different from JavaScript, it actually maps pretty closely to its generated output.
Later on, we delved into some of CoffeeScripts' unique and wonderful additions, like list comprehensions, destructuring assignment, and its class syntax, as well as many more convenient and powerful features such as string interpolation, ranges, splats, and array slicing. My goal in this chapter was to convince you that CoffeeScript is a superior alternative to JavaScript, and I have tried to do so by showing the differences between them.
Although I have previously said "it's just JavaScript", I hope that you'll appreciate that CoffeeScript is a wonderful and modern language in its own right, with brilliant influences from other great scripting languages. I can still write a great deal about the beauty of the language, but I feel that we have reached the point where we can dive into some real world CoffeeScript and get to appreciate it "in the wild", so to speak.
Michael Erasmus has been developing software for over 10 years. He has been a C programmer for quite a few of them, but has luckily been enlightened enough to become an open source zealot during the last few years. He's interested in all manner of science and technology, but tends to dwell on things such as elegant and eccentric programming languages, machine learning and statistics, web development, Internet startups, and civic hacking.
He is currently working at 22seven. When he's not sitting in front of the computer, he likes pulling faces to amuse his baby son, apologizing to his wonderful wife for sitting in front of a computer all day, or arguing endlessly with friends, family, colleagues, and random strangers. He lives near the beach in Muizenberg, Cape Town and loves it. About this book CoffeeScript is a young but popular language that makes web programming fun and more productive. Publication date: December Publisher Packt.
Pages ISBN Chapter 1. Why CoffeeScript? CoffeeScript syntax. Semicolons and braces. There is no need of using braces in in CoffeeScript except while calling the functions with parameters and dealing with the ambiguous code and we have to replace the function definition function with an arrow mark as shown below. Remove the unnecessary return statements, since CoffeeScript implicitly returns the tailing statements of a function. Callback is an asynchronous equivalent for a function.
A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks.
Here are some notable exceptions:. This list may be incomplete, and excludes versions of Node that support newer features behind flags; please refer to node. You can run the tests in your browser to see what your browser supports. It is your responsibility to ensure that your runtime supports the modern features you use; or that you transpile your code.
When in doubt, transpile. The command-line version of coffee is available as a Node. The core compiler however, does not depend on Node, and can be run in any JavaScript environment, or in the browser see Try CoffeeScript. To install, first make sure you have a working copy of the latest stable version of Node.
You can then install CoffeeScript globally with npm :. The coffee and cake commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so.
This allows different versions of CoffeeScript to be installed globally and locally. Once installed, you should have access to the coffee command, which can execute scripts, compile. The coffee command takes the following options:. The compile method has the signature compile code, options where code is a string of CoffeeScript code, and the optional options is an object with some or all of the following properties:.
CoffeeScript 2 generates JavaScript that uses the latest, modern syntax. The runtime or browsers where you want your code to run might not support all of that syntax.
To make things easy, CoffeeScript has built-in support for the popular Babel transpiler. You can use it via the --transpile command-line option or the transpile Node API option. You need to provide it with a configuration so that it knows what to do. One way to do this is by creating a. Babel supports other ways , too.
A minimal. This lets you use transpilers other than Babel, and it gives you greater control over the process. There are many great task runners for setting up JavaScript build chains, such as Gulp , Webpack , Grunt and Broccoli.
CoffeeScript itself will output Array. This reference is structured so that it can be read from top to bottom, if you like. Later sections use ideas and syntax previously introduced.
Familiarity with JavaScript is assumed. In all of the following examples, the source CoffeeScript is provided on the left, and the direct compilation into JavaScript is on the right. The CoffeeScript on the left is editable, and the JavaScript will update as you edit. First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. The implicit call wraps forward to the end of the line or block expression.
Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. Functions may also have default values for arguments, which will be used if the incoming argument is missing undefined.
Like JavaScript and many other languages, CoffeeScript supports strings as delimited by the " or ' characters. Single-quoted strings are literal. You may even use interpolation in object keys. Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.
The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code. The CoffeeScript literals for objects and arrays look very similar to their JavaScript cousins.
When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to YAML. CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name.
In CoffeeScript, comments are denoted by the character to the end of a line, or from to the next appearance of. Comments are ignored by the compiler, though the compiler makes its best effort at reinserting your comments into the output JavaScript after compilation. The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.
Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.
The safety wrapper can be disabled with the bare option , and is unnecessary and automatically disabled when using modules. This is intentional ; we feel that the simplicity gained by not having to think about variable declaration outweighs the benefit of having three separate ways to declare variables.
As with functions and other block expressions, multi-line conditionals are delimited by indentation. CoffeeScript can compile if statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular if statement on a single line.
The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ES adopted this feature as their rest parameters. Comprehensions replace and compile into for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.
Note how because we are assigning the value of the comprehensions to a variable in the example above, CoffeeScript is collecting the result of each iteration into an array. Sometimes functions end with loops that are intended to run only for their side-effects. Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.
If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be inherited from the prototype, use for own key, value of object. To iterate a generator function, use from. See Generator Functions. The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used as an expression, returning an array containing the result of each iteration through the loop.
For readability, the until keyword is equivalent to while not , and the loop keyword is equivalent to while true. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments. Ranges can also be used to extract slices of arrays. With two dots Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.
The same syntax can be used with assignment to replace a segment of an array with new values, splicing it. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution in the function below. Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure.
This lets you do useful things, like assign the result of a comprehension to a variable:. As in YAML , on and yes are the same as boolean true , while off and no are boolean false. You can use in to test for array presence, and of to test for JavaScript object-key presence. In a for loop, from compiles to the ES of. Note that if the compiler knows that a is in scope and therefore declared, a? The reverse also holds for not a?
If a variable might be undeclared, the compiler does a thorough check. This is what JavaScript coders should be typing when they want to check if a mystery variable exists.
The accessor variant of the existential operator?. Use it instead of the dot accessor. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left.
0コメント