Performance Zone is brought to you in partnership with:

I've been in the world of software development for 14+ years working with most mainstream programming languages at some point. Chad is a DZone MVB and is not an employee of DZone and has posted 38 posts at DZone. You can read more from them at their website. View Full User Profile

10 Tips and Tricks on How to Improve Your Productivity with Coffeescript

06.13.2012
| 4250 views |
  • submit to reddit

Post to Twitter

CoffeeScript for those that might not know is a language that compiles into JavaScript. Today I’m going to go over ten things that will help you when working with CoffeeScript.

Tip 1: Splats
Splats in CoffeeScript allow you to have functions that take a variable numbers of arguments. Here is an example:

mySplat = (args...) ->
    console.log "#{args.join()}"
 
mySplat(1,2,3,4,5)

Output:

1,2,3,4,5

Tip 2: Working with Booleans
For booleans you can use on and yes and they will work just like true, whereas off and no are treated like false. Here is an example of what you can do:

lightSwitch = false
 
if lightSwitch is off
    console.log 'Turn on the lights!'
else
    console.log 'Turn off the lights!'

Output:

Turn on the lights!

Tip 3: The Existential Operator
The Existential Operator checks for the existence of a variable. Here is an example:

myValue1 = 'Hello World'
 
if myValue1? then console.log myValue1
 
# This next variable doesn't exist
if myValue2? then console.log myValue2

Output:

Hello World

This also means you can do things like this:

class MyClass
    myFunction1: (val) ->
        console.log "You passed #{val} to myFunction1"
 
myClass = new MyClass()
myClass?.myFunction1(123)
 
# This next function doesn't exist
myClass.myFunction2?(123)

Since myFunction2 doesn’t exist in MyClass you will only see the following (no errors raised, etc.):

You passed 123 to myFunction1

Tip 4: Using ‘in’ to test if a value is contained in an array
Using the keyword in you can quickly check if a value is inside of an array. Here is an example:

foods = ['apple', 'orange', 'potatoe', 'strawberries']
 
if 'potatoe' in foods then console.log 'Found potatoe'
if 'carrot' in foods then console.log 'Found carrot'

Output:

Found potatoe

Tip 5: Iterating an Object
I’ll create a simple object and show how easy it is to iterate through it getting the keys and values.

dragon =
    level: 1
    alignment: 'neutral'
    age: 'Youngling'
    attack: 'Fire'
    damage: '1d4'
 
for key, val of dragon
    console.log "#{key}: #{val}"

Output:

level: 1alignment: neutralage: Younglingattack: Firedamage: 1d4

Tip 6: Classes
Class are dead simple. I have an existing article which I will refer you to, however here is a simple example of creating a class and using constructors and inheritance:

class Spaceship
 
    constructor: (@speed = 1, @spaceShipType = 'spaceship') ->
        console.log "New #{@spaceShipType} created with a speed of #{@speed}"
 
    move: () ->
        console.log "The #{@spaceShipType} is moving now at a speed of #{@speed}"
 
class FlyingSaucer extends Spaceship
 
    constructor: ->
        super 5, 'Flying Saucer'
 
    useDeathRay: ->
        console.log "The flying saucer is using a death ray!"
 
spcshp = new Spaceship()
spcshp.move()
 
flySaucr = new FlyingSaucer()
flySaucr.move()
flySaucr.useDeathRay()

Tip 7: A simple shortcut for ‘this’
There is a simple shortcut for this and it is the @ symbol.

class MyClass
 
    constructor: (@greeting) ->
        console.log "You set the greeting as: #{@greeting}"
 
    greet: ->
        console.log "You said: #{@greeting}"
 
myClass = new MyClass('Bonjour')
myClass.greet()

You can see @greeting is available to the class functions.

Output:

You set the greeting as: BonjourYou said: Bonjour

Tip 8: Default Values
Using the above class I can actually set a default greeting within the constructor (or any other function). Here is the modified example taken from above:

class MyClass
 
    constructor: (@greeting = 'Hola') ->
        console.log "You set the greeting as: #{@greeting}"
 
    greet: ->
        console.log "You said: #{@greeting}"
 
myClass = new MyClass()
myClass.greet()

Output:

You set the greeting as: HolaYou said: Hola

Tip 9: Block Strings
Very easy to use and you don’t have to escape quotes or apostrophes as it is done for you.

markup = """
    <form action="/" method="post">
        <input type="submit" />
    </form>
"""
 
console.log markup

Output:

<form action="/" method="post">    <input type="submit" /></form>

Tip 10: String Interpolation
I’ve been using this through several of my examples already. Anything in a double quote will get parsed so you can embed a variable like this:

myValue = 'Hello World'
 
console.log "You said: #{myValue}"

You can also do things like this though:

val1 = 5;
val2 = 7;
 
console.log "Your answer for 5 * 7 is: #{val1 * val2}"

Output:

Your answer for 5 * 7 is: 35

You could do this as well:

console.log "Your answer for 5 * 7 is: #{5 * 7}"
Published at DZone with permission of Chad Lung, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)