Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
CoffeeScript Application Development
CoffeeScript Application Development

CoffeeScript Application Development: What JavaScript user wouldn't want to be able to dramatically reduce application development time? This book will teach you the clean, elegant CoffeeScript language and show you how to build stunning applications.

Arrow left icon
Profile Icon Ian Greenleaf Young
Arrow right icon
$9.99 $28.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
eBook Aug 2013 258 pages 1st Edition
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Ian Greenleaf Young
Arrow right icon
$9.99 $28.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
eBook Aug 2013 258 pages 1st Edition
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

CoffeeScript Application Development

Chapter 2. Writing Your First Lines of CoffeeScript

In this chapter, we will dive into CoffeeScript headfirst. We'll look at all the simple data types and control structures, and find out how CoffeeScript helps us deal with them more simply and expressively. We'll discover some neat tricks that save us keystrokes and reduce the likelihood of errors in our code. And we'll peek under the hood to see how some of the CoffeeScript magic is happening.

In this chapter, you can expect to:

  • Learn CoffeeScript syntax for many common operations

  • Learn how to use standard data types and control structures in CoffeeScript

  • See how the CoffeeScript we write maps back to JavaScript once compiled

Following along with the examples


I implore you to open up a console as you read this chapter and try out the examples for yourself. You don't strictly have to; I'll show you any important output from the example code. However, following along will make you more comfortable with the command-line tools, give you a chance to write some CoffeeScript yourself, and most importantly, will give you an opportunity to experiment. Try changing the examples in small ways to see what happens. If you're confused about a piece of code, playing around and looking at the outcome will often help you understand what's really going on.

The easiest way to follow along is to simply open up a CoffeeScript console. Remember how we did that in the previous chapter? Just run this from the command line to get an interactive console:

coffee

If you'd like to save all your code to return to later, or if you wish to work on something more complicated, you can create files instead and run those. Give your files the .coffee...

CoffeeScript basics


Let's get started! We'll begin with something simple:

x = 1 + 1

You can probably guess what JavaScript this will compile to:

var x;
x = 1 + 1;

Statements

One of the very first things you will notice about CoffeeScript is that there are no semicolons. Statements are ended by a new line. The parser usually knows if a statement should be continued on the next line. You can explicitly tell it to continue to the next line by using a backslash at the end of the first line:

x = 1\
  + 1

It's also possible to stretch function calls across multiple lines, as is common in "fluent" JavaScript interfaces:

"foo"
  .concat("barbaz")
  .replace("foobar", "fubar")

You may occasionally wish to place more than one statement on a single line (for purely stylistic purposes). This is the one time when you will use a semicolon in CoffeeScript:

x = 1; y = 2

Both of these situations are fairly rare. The vast majority of the time, you'll find that one statement per line works great. You might feel a pang...

Calling functions


Function invocation can look very familiar in CoffeeScript:

console.log("Hello, planet!")

Other than the missing semicolon, that's exactly like JavaScript, right? But function invocation can also look different:

console.log "Hello, planet!"

Whoa! Now we're in unfamiliar ground. This will work exactly the same as the previous example, though. Any time you call a function with arguments, the parentheses are optional. This also works with more than one argument:

Math.pow 2, 3

While you might be a little nervous writing this way at first, I encourage you to try it and give yourself time to become comfortable with it. Idiomatic CoffeeScript style eliminates parentheses whenever it's sensible to do so. What do I mean by "sensible"? Well, imagine you're reading your code for the first time, and ask yourself which style makes it easiest to comprehend. Usually it's most readable without parentheses, but there are some occasions when your code is complex enough that judicious use of parentheses...

Control structures


Control structures (such as if, else, and so on) in CoffeeScript share a foundation with JavaScript. We'll start out with some constructions that will feel familiar except some slightly different syntax. However, we'll then build on those basics and explore some new ways to express control flow.

So far, most of the CoffeeScript syntax we have covered has been somewhat superficial. Less punctuation makes code more readable (and prettier!), but CoffeeScript promises more than that. As we work through these control structures, you'll get a taste of some improvements that make CoffeeScript a more expressive language. Code isn't just machine instructions, it's also a form of communication. Good code not only works as intended, but communicates to other humans about what it is doing and how it is doing that. In this section we'll see some ways that CoffeeScript helps you communicate more effectively.

Using if statements

The first structure we'll look at is the standard if statement...

Comparison operators


Now that we know how to use these control structures, let's learn about some comparison operators we can use to test the truthfulness of useful questions. There's one big surprise in here, so let's get that out of the way. == and != in CoffeeScript don't compile to their equivalents in JavaScript.

1 == 2
3 != 4

becomes:

1 === 2;
3 !== 4;

Note

According to the CoffeeScript documentation, this decision was made because "the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages".

Most JavaScripters recommend using === and !== exclusively, so this is simply enshrining that best practice. If you wish to know more about this recommendation, read http://www.impressivewebs.com/why-use-triple-equals-javascipt/.

Other than that surprise, the other common JavaScript operators are all present and work as you might expect.

if 1 < 2 && 3 >= 2
  if false || true
    if !false
      console.log "All is well."

However...

Arrays


Arrays, at their most simple, look very similar to JavaScript.

languages = [ "english", "spanish", "french" ]
console.log languages[1]

You may use a trailing comma and it will be compiled away:

languages = [
  "english",
  "spanish",
  "french",
]

becomes:

var languages;
languages = ["english", "spanish", "french"];

Many people prefer this style, as it makes it easier to change the contents of an array or object. And you'll be thankful for this safeguard if you've ever left a trailing comma in a JavaScript array, only to discover (always at a very inconvenient time) that it causes an execution-halting error in one particular browser. The browser in question will remain unnamed for the sake of our collective blood pressure. I want this book to be a book about nice things. Happy things.

If you're feeling daring, you can eschew commas altogether. That's right! When the members of your array are declared on separate lines, you may omit the commas and CoffeeScript will still know what to do.

languages...

Simple objects


You have no doubt spent a lot of time working with objects in JavaScript. They are the most versatile data structure in the language, and JavaScript encourages heavy use of them. CoffeeScript keeps all that great support for objects, and adds a few helpful features for dealing with them.

Declaring an object looks very familiar. Let's record a few biographical details:

author = { name: "Ian", age: 26 }

We can still access object properties like we do in JavaScript:

author.name
author["age"]
author.favoriteLanguage = "CoffeeScript"

Just like CoffeeScript arrays, if we declare the object properties on different lines, we can optionally omit the commas.

authorsBicycle = {
  color: "black"
  fenders: true
  gears: 24
}

That's not all! We can also omit the curly braces. This is possible on both the single-line and multi-line versions.

author = name: "Ian", age: 26, favoriteLanguage: "CoffeeScript"
authorsBicycle =
  color: "black"
  fenders: true
  gears: 24

This even works with nested objects...

Summary


We've covered a lot of ground in this chapter. We learned:

  • How to use variables.

  • How to call functions.

  • How to use if/else statements and their counterpart, unless.

  • How to use natural-language aliases to make our comparison statements more readable.

  • How to declare arrays, and iterate through their contents in a number of different ways.

  • How to declare and iterate over objects.

Not only did we learn about all those things, but we made sure to avoid a few common mistakes, and learned why it was possible to make those mistakes. We've compared many of the CoffeeScript statements to the compiled JavaScript, so hopefully you're developing a good mental map of how CoffeeScript translates to JavaScript.

Now that we've got a solid handle on the basics, we're ready to start building our application. In the next chapter, we'll begin development of a small web application to help manage a pet shop. We'll need all of the skills we learned in this chapter, and we'll be learning a few more as we work!

Left arrow icon Right arrow icon

Key benefits

  • Learn the ins and outs of the CoffeeScript language, and understand how the transformation happens behind the scenes
  • Use practical examples to put your new skills to work towards building a functional web application, written entirely in CoffeeScript
  • Understand the language concepts from short, easy-to-understand examples which can be practised by applying them to your ongoing project

Description

JavaScript is becoming one of the key languages in web development. It is now more important than ever across a growing list of platforms. CoffeeScript puts the fun back into JavaScript programming with elegant syntax and powerful features. CoffeeScript Application Development will give you an in-depth look at the CoffeeScript language, all while building a working web application. Along the way, you'll see all the great features CoffeeScript has to offer, and learn how to use them to deal with real problems like sprawling codebases, incomplete data, and asynchronous web requests. Through the course of this book you will learn the CoffeeScript syntax and see it demonstrated with simple examples. As you go, you'll put your new skills into practice by building a web application, piece by piece. You'll start with standard language features such as loops, functions, and string manipulation. Then, we'll delve into advanced features like classes and inheritance. Learn advanced idioms to deal with common occurrences like external web requests, and hone your technique for development tasks like debugging and refactoring. CoffeeScript Application Development will teach you not only how to write CoffeeScript, but also how to build solid applications that run smoothly and are a pleasure to maintain.

Who is this book for?

If you are a JavaScript developer who wants to save time and add power to your code, then this is the book that will help you do it. With minimal fuss you will learn a whole new language which will reduce your application development time from weeks to days.

What you will learn

  • Write CoffeeScript everywhere, and compile it to JavaScript that can run anywhere
  • Discover techniques to manage a complicated codebase and ever-changing requirements
  • Drop the semicolons with CoffeeScript s clean, powerful syntax
  • Build for loops, if statements, and functions without all the extra keystrokes
  • Keep your code clean and organized with classes and inheritance
  • Use advanced CoffeeScript idioms to deal with the needs of a growing application
  • Debug effectively with source maps
  • Integrate CoffeeScript into your project seamlessly with Rails, Brunch, and other web frameworks
  • Utilize CoffeeScript for server-side software with Node.js

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2013
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162674
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 26, 2013
Length: 258 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162674
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 103.98
Object-Oriented JavaScript - Second Edition
$54.99
CoffeeScript Application Development
$48.99
Total $ 103.98 Stars icon
Banner background image

Table of Contents

11 Chapters
Running a CoffeeScript Program Chevron down icon Chevron up icon
Writing Your First Lines of CoffeeScript Chevron down icon Chevron up icon
Building a Simple Application Chevron down icon Chevron up icon
Improving Our Application Chevron down icon Chevron up icon
Classes in CoffeeScript Chevron down icon Chevron up icon
Refactoring with Classes Chevron down icon Chevron up icon
Advanced CoffeeScript Usage Chevron down icon Chevron up icon
Going Asynchronous Chevron down icon Chevron up icon
Debugging Chevron down icon Chevron up icon
Using CoffeeScript in More Places Chevron down icon Chevron up icon
CoffeeScript on the Server Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(6 Ratings)
5 star 83.3%
4 star 16.7%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Ian F Lunderskov Dec 02, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
ian has written an excellent introduction to coffeescript with this book. opening with some base features to ease into the syntax, he builds logically and incrementally from basic examples to more fully realized application examples. as a ruby user, the syntax made a lot of sense to me, but i was still impressed by how ian explained certain concepts for those that may not have a familiarity with some more modern languages. in addition to building your coffeescript knowledge progressively, ian also takes the time to point out how the use of coffeescript can help avoid potential pitfalls in javascript, with context of when this pitfalls could occur.overall, it was a pleasure to read, with a conversational tone that made the material come easily. i highly recommend it for anyone thinking of trying out coffeescript (which i would in turn also highly recommend). note that the book does expect the reader to have some background in javascript (as that is what coffeescript compiles down to), and that it is not designed for a reader with no programming experience.
Amazon Verified review Amazon
Aydan Apr 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
My son loved this and said it was very informative
Amazon Verified review Amazon
Tom Cully Nov 25, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Ian Young's book makes for an excellent 'bootstrap' to Coffeescript programming, covering everything from installing dependencies and setting up a development environment - for Mac, Windows and Linux - to producing real world applications. Although some experience with Javascript will be helpful, the book assumes no prior knowledge and can be used to learn Coffeescript from a standing start.For seasoned Coffeescript coders, the book illustrates and teaches deep knowledge of the syntax and structure of the language, and even for professionals it's likely you will learn a few new tricks or ways to make your code more efficient and readable whether coding, debugging, testing, building or during deployment. Coffeescript for emerging Clientside frameworks is covered for Backbone, Ember and more - not to mention serverside code using node.js or Ruby/Rails.I would highly recommend 'Coffeescript Application Development' for professionals and hobbyist coders alike, whether you're just interested the language, are starting a major Coffeescript project, or are already a Coffeescript coder looking for patterns and best practices in Jeremy Ashkenas' emerging language.
Amazon Verified review Amazon
Jack Miller Nov 29, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've never heard of CoffeeScript ever before never-mind wrote it. But the first page started of by saying what it is and where it's used. It also says how it's different from other languages which I was interested in because I didn't actually know there was a different way for code to be compiled.So who is this book for? This isn't a beginners book by no means, it is however a beginners book for CoffeeScript however you need to have some experience in Web Design under your belt before you will start to understand this book. This is because CoffeeScript is a web application language and when it is compiled it isn't compiled to machine code, instead it's compiled into JavaScript so you can see why it's useful to know Javascript.However don't let it put you off, if you're interested in Web Applications then you'll be interested in CoffeeScript and you can easily jump onto Code Academy or W3Schools and learn the basics of both JavasScript and HTML.In the first section of the book it's going to teach you how to install CoffeeScript on Linux, Mac and Windows so don't fear if you think your operating system isn't compatible. After the book has taught you how to install CoffeeScript you are then set to write your first program. If you've ever programmed before you'll find the layout is very similar to other languages and follows the same principles - it wouldn't surprise me if you managed to pick it up quickly. The second section looks at everything you need to know when coding in this language. It teaches you Comments, If statements, loops, arrays, unless statements and everything you'll need to get started.In the third section you will start to develop your very first web application in CoffeeScript. The first application they create is 'Ians Pet Shop' and as the book goes through the author adds improvements and new features to his application as he goes along showing you every step of the way.By the end of the book you will have the knowledge to go and start creating your own Web applications. If you need a CoffeeScript Book then this is the one you should buy if you are just starting out and want to learn more. The author explains things in depth and helps you every step of the way showing you what he's doing and why he's doing it. I give this book a 5/5 as it is very well laid out in a step by step process and you can clearly see code separate from instructions.
Amazon Verified review Amazon
K. Melby Dec 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book starts from a bare-bones webpage of simple HTML and CSS then slowly layers new features built in CoffeeScript into it chapter by chapter. By the final chapter you have a fully baked web-app running from server-side code written again in CoffeeScript.As a developer who has dabbled in JavaScript but isn't an expert in this part of web-development the tour of the language and the side-by-side comparison of CoffeeScript features and their analogies in JavaScript taught me a ton about both languages. The book can be consumed pretty quickly by someone with a strong programming background, but the explanations are clear enough that the novice should be able to dive in easily. The author takes enlightening detours into common best-practices like when to avoid inheritance and gives good refreshers on concepts like memoization.One particularly useful section of this book is the last few chapters which introduces other libraries and technologies to help the reader get their feet wet with async.js, Backbone.js, Node.js and a few others. Getting a view of the author's favorite libraries was a good way to get my feet wet in figuring out which of the overwhelming number of open-source tools I should be using.The only thing that feels like it's missing from this book is a section on testing. Any application with hopes of remaining stable has some kind of test suite to make sure it's up to snuff after each change to the code. So, it would be very nice to have an into into some JavaScript testing tools and how best to use them with CoffeeScript.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.