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
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
Paperback Aug 2013 258 pages 1st Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Ian Greenleaf Young
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (6 Ratings)
Paperback Aug 2013 258 pages 1st Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781782162667
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 79.98
Object-Oriented JavaScript - Second Edition
€41.99
CoffeeScript Application Development
€37.99
Total 79.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.