A taste of CoffeeScript (part 2)

Default avatar.
May 29, 2013
A taste of CoffeeScript (part 2).

thumbnailIn the first part of this article about CoffeeScript, you saw its basic capabilities; but let's be honest, most of the time we use the jQuery library to help us write our JavaScript and what I showed you in the first part was just vanilla JavaScript.

In this part we will join CoffeeScript, LocalStorage and jQuery to create a simple contact manager where we can save someone's number, name and also check if that person is a friend, and with the help of LocalStorage this contact manager will save your contacts when you refresh your page.

You can see the demo of what we will be creating in this demo I built.


As you saw in the demo, our HTML will be the form and a simple empty <ul> that we will fill later with the names and numbers:

<form action="#" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required autofocus />
<label for="number">Number</label>
<input tpe="tel" name="number" id="number" required />
<label for="friend">Is he a friend?</label>
<input type="checkbox" name="friend" id="friend">
<input type="submit" id="submit" value="Add" />
<ul id="numbers"></ul>

Even though this form has a method and action we will later block the default action with JavaScript to stop it actually reloading the page and jumping when it is submitted. Instead we'll just fill the numbers unordered list with what is in the form's inputs.

The CoffeeScript

Now we will get into the best part of this article: talking about CoffeeScript and jQuery together, two tools that were made to make our JavaScript development simpler and more productive.

Let's think about what we want this app to do in bullet points before the coding:

  • Add the class checked if the checkbox is checked and remove it if not;
  • check for a click event on the submit button;
  • get the values of the number and name;
  • place these values on our page;
  • add all the names and numbers to LocalStorage;
  • delete everything we have typed into the form;
  • prevent the form submitting;
  • read and display any data held in LocalStorage.

Now we've got all of this straight we can start from the top. To add the checked class we need to check for a click and then toggle the class on every single class, we have already seen how to construct functions in CoffeeScript in part 1, so:

$('#friend').click -> $(this).toggleClass 'checked'

The next thing we need to is check for a click on the submit button and store some variables that we will be needing further down the road:

$('#submit').click ->
 ul = $('#numbers')
 number = $('#number').val()
 name = $('#name').val()

In this step we have defined our function and the variables we need later, the ul variable holds the unordered list that will contain all the names and numbers and the next two will store whatever we type on the inputs.

This is the part where we grab all the values we have and prepend a list item for each number we have. Remember we want to style things a little bit differently if the contact is a friend, so we will check the class of the checkbox and add different classes to our list items accordingly. For that we will use a simple if statement as described in part 1:

if $('#friend').hasClass 'checked'
$(ul).prepend '<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>'
$(ul).prepend '<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>'

The base of our app is ready but if you reload the page you will see that all the numbers are gone, so we need to add the contents of the numbers to LocalStorage and we will call it contacts:

localStorage.setItem 'contacts', $(ul).html()

What we are doing is naming what we want to save first, and then after the comma we declare the value to be saved. in this case we will save the contents of the unordered list.

With this line done, we have all the numbers and names in LocalStorage so let's add the final touches to the function by resetting the form and then returning false to ensure the page doesn't reload:

return false 

The function is now complete and all we need to do now is check if we have something in LocalStorage with the name of contacts and if we do we just need to place that on the page:

if localStorage.getItem 'contacts'
 $('#numbers').html localStorage.getItem 'contacts'

All we are doing is checking and then placing the contents of that item on the page. With this last touch our little contact manager is done and the full CoffeeScript code used was:

$('#friend').click -> $(this).toggleClass 'checked'

$('#submit').click ->
ul = $('#numbers')
number = $('#number').val()
name = $('#name').val()
if $('#friend').hasClass 'checked'
$(ul).prepend '<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>'
$(ul).prepend '<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>'
localStorage.setItem 'contacts', $(ul).html()
return false

if localStorage.getItem 'contacts'
$('#numbers').html localStorage.getItem 'contacts'

And if we run this code through the compiler we end up with the following JavaScript:

$('#friend').click(function() {
return $(this).toggleClass('checked');

$('#submit').click(function() {
var name, number, ul;
ul = $('#numbers');
number = $('#number').val();
name = $('#name').val();
if ($('#friend').hasClass('checked')) {
$(ul).prepend('<li class="friend"><span>Name: ' + name + '<br/> Number: ' + number + '</span></li>');
} else {
$(ul).prepend('<li><span>Name: ' + name + ' <br/>Number: ' + number + '</span></li>');
localStorage.setItem('contacts', $(ul).html());
return false;

if (localStorage.getItem('contacts')) {

Compare both we can see that the CoffeeScript has 587 words and 14 lines while the Javascript one has 662 words and 21 lines, and if we compare legibility we can see that the CoffeeScript is substantially more legible than the JavaScript equivalent. If in this type of simple application CoffeeScript can save you 7 lines of code imagine how much it would save in full blown application!


I hope this article has given you a better idea of CoffeeScript and how it can improve your day-to-day JavaScript coding. The code written in this article isn't meant to be cleanest or easiest JavaScript, rather it was intended to illustrate using CoffeeScript. I hope now that you can see how powerful it is with jQuery and you consider using this great little language in your daily coding because it will most definitely save you hours of typing.

Do you use CoffeeScript? How useful do you find it day-to-day? Let us know in the comments.

Featured image/thumbnail, coffee image via Shutterstock.

Sara Vieira

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website.

Read Next

3 Essential Design Trends, December 2023

While we love the holidays, too much of a seasonal theme can get overwhelming. Thankfully, these design trends strike a…

10 Easy Ways to Make Money as a Web Designer

When you’re a web designer, the logical way to make money is designing websites; you can apply for a job at an agency,…

The 10 Most Hated Fonts of All Time

Remember when Comic Sans wasn’t the butt of the jokes? Long for the days when we actually enjoyed using the Impact…

15 Best New Fonts, November 2023

2023 is almost over, and the new fonts are still coming thick and fast. This month, we’ve found some awesome variable…

Old School Web Techniques Best Forgotten

When the web first entered the public consciousness back in the 90s, it was primarily text-based with minimal design…

20 Best New Websites, November 2023

As the nights draw in for the Northern hemisphere, what better way to brighten your day than by soaking up some design…

30 Amazing Chrome Extensions for Designers and Developers

Searching for a tool to make cross-platform design a breeze? Desperate for an extension that helps you figure out the…

Exciting New Tools for Designers, November 2023

We’ve got a mix of handy image helpers, useful design assets, and clever productivity tools, amongst other treats. Some…

The Dangers of Doomscrolling for Designers and How to Break Free

As a creative professional, navigating the digital realm is second nature to you. It’s normal to follow an endless…

From Image Adjustments to AI: Photoshop Through the Years

Remember when Merriam-Webster added Photoshop to the dictionary back in 2008? Want to learn how AI is changing design…

3 Essential Design Trends, November 2023

In the season of giving thanks, we often think of comfort and tradition. These are common themes with each of our three…

30 Obsolete Technologies that will Perplex Post-2000s Kids

Remember the screech of dial-up internet? Hold fond memories of arcade machines? In this list, we’re condensing down 30…