Avoid CoffeeScript & use ES6!

Those of you that follow my blog might have noticed how fond I am to some of CoffeeScript’s conveniences. They are excellent, but it’s time to leave them behind and start using ES6. Most of CoffeeScript’s goodies already exist in ES6 (with some syntax changes), and your code is guaranteed to be future proof. And if time spent learning CoffeeScript feels like a waste, there’s good news – with a solid CoffeeScript base, transitioning to ES6 will be a piece of cake!

Coffeescript gotchas (part 3): Switch statement and loops

Welcome to the third part of Coffeescript gotchas. If you haven’t yet read the first and second part of the series I strongly recommend to have a look. The main topic today is loops plus the switch statement. CoffeeScript offers a lot of enchantments and syntactic sugar to them.

Update: Table of contents

Switch statement

At last, an easier way to write switch statements. If your switch case contains a single line of code, you can write the entire thing in a single line using the then keyword (see second example).

name = "John"

# normal switch statement
switch name
  when "John"
    console.log "This guy rocks!"
  when "Jon"
    console.log "Still cool guy"
  else
    console.log "Good lad."
    
# switch statement using the then keyword
switch name
  when "John" then console.log "This guy rocks!"
  when "Jon" then console.log "Still cool guy"
  else console.log "Good lad."

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

For Loops

For loops have many flavors and great potential in CoffeeScript. You can loop through arrays and objects and still keep your code clean and hassle-free. Just take a deep breath and try to absorb as many flavours as you can. They can all come very handy.

Arrays

Iterating Arrays have never been easier…

arr = ["Ned Stark", "Jon Snow", "Arya Stark", "Jaime Lannister"]

# basic array iteration
for name in arr
    console.log name

# array iteration (with index)
for name , i in arr
    console.log "#{i}: #{name}"

# array filtering (with index)
for name, i in arr when name.indexOf "J" is 0
    console.log "#{i}: #{name}"

# array iteration for every second item
for name , i in arr by 2
    console.log "#{i}: #{name}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

Objects

Looping through an object’s key/value pairs is also very easy. You can also loop through just the direct key/value pairs (not the inherited ones) by using the own keyword (which will use the hasOwnProperty method under the hood).

ned =
  name : "Ned Stark"
  house : "Stark"
  words : "Winter is coming"

# print all properties of an object
for key, value of ned 
  console.log "#{key} : #{value}"

# print all own properties of an object
for own key, value of ned
  console.log "#{key} : #{value}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

While Loops

The while loop has 3 syntax flavors to make your code more descriptive and your life easier. Try to use unless instead of while not, as it’s easier and preferable.

# Normal while
num = 10
while num
  console.log num
  num--

# while not
num = 10
while not (num is 0)
  console.log num
  num--

# exactly the same as the above example
num = 10
until num is 0
  console.log num
  num--

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

As you can see CoffeeScript is very handy when it comes to loops. Keep in mind and stay tuned for the fourth and final part of the Coffeescript gotchas series where we’ll have a look at the syntactic sugar that CoffeeScript provides on Scope and Objects.

Coffeescript gotchas (part 2): Operators and aliases

For this second part of the series, we’ll dig into CoffeeScript operators and their aliases, which make our lives easier and our code much cleaner and more expressive. In case you missed the first part I recommend you have a look at it, I’m sure you’ll find something interesting.

Update: Table of contents

Basic operators and their aliases

When it comes to if statements (and not only them), CoffeeScript provides many syntax aliases that keep our code clean and readable. For starters, we can forget triple equals (===) and negative double equals (!==), and use their easier aliases, the is and isnt keywords. Have a look at the example below.

name = "John"

if name is "John" # true ( is equals === )
  console.log('is demonstration')
  
if name isnt "Johnny" # false ( isnt equals !== )
  console.log('isnt demonstration')

See the Pen Coffeescript gotchas (part 2): operators and aliases by John Tsevdos (@tsevdos) on CodePen.

You can also use the not keyword and get rid of Javascript’s exclamation mark (!) operator. Much more readable!

if not false # compiles as if (!false) in Javascript
  console.log('not demonstration')

See the Pen Coffeescript gotchas (part 2): operators and aliases by John Tsevdos (@tsevdos) on CodePen.

Want to make it even more readable? You can even replace the if not statement with the much more descriptive  unless keyword. It makes more sense in some cases:

# if not === unless

person =
  isRunning : false,
  startRunning : ->
  	console.log('start running!')

if not person.isRunning
  person.startRunning()

unless person.isRunning
  person.startRunning()

See the Pen jKLCH by John Tsevdos (@tsevdos) on CodePen.

Finally, you can forget boolean operators such as double ampersands (&&) and the double vertical bars (||) and start using the much more convenient and and or keywords. The real fun starts when you combine all these new keywords. Writing Javascript becomes as easy as english!

name = 'John'
sex  = 'male'
isCool = true

if name is "John" and sex is "male" # compiles as if ( name === "John" && sex === "male" )
  console.log('do something')

if name is "John" or isCool is true # compiles as if ( name === "John" || isCool === true )
  console.log('do something else')

See the Pen JwuiD by John Tsevdos (@tsevdos) on CodePen.

Ternary Operator

The ternary Operator in CoffeeScript looks a bit tricky at first, and in my opinion is probably the only operator that actually looks better in plain good old Javascript, but in case you need to use it, it looks like this:

maxValue = 10
minValue = 1

value = if 10 > 0 then 5 else 15 # value = 5

document.write(value)

See the Pen zKaqC by John Tsevdos (@tsevdos) on CodePen.

CoffeeScript’s question mark operator

This is a unique CoffeeScript feature that checks if a variable (or property) has a value. So it basically tests if the value isn’t null or of type undefined. Keep in mind that this is not testing if a value is “falsey” (like a empty string, number 0, empty array, etc.). For more details on “truthy” and “falsy” values have a look at this excellent article on Sitepoint.

if name? # compiles as if ( name !== null || name !== "undifined" )
  document.write('Safely use name value.')

See the Pen wihJj by John Tsevdos (@tsevdos) on CodePen.

You can also use this feature on object properties or when you want to check if the value isn’t null or of type undefined. Have a look at the examples below and discover a nicely added feature that will save you a lot of typing…

person =
	name: 'John'
  
console.log( person?.name )

nullName = null
nullName?= "Johnny"

console.log( nullName )

nullName = null
otherName = nullName ? "Yiannis"

console.log( otherName )

See the Pen GEksz by John Tsevdos (@tsevdos) on CodePen.

The OR operator (on value assignments)

It looks better and more compact…

name = false # falsy value

name ||= "John" # name || (name = "John");

console.log(name)

See the Pen pmfBz by John Tsevdos (@tsevdos) on CodePen.

Chaining comparison

Another CoffeeScript only feature. If your condition is between a range you can finally combine them, just like in algebra. Nicely done.

x = 8

if 0 <= x <= 10 # compiles to if ( 0 <= x  && x <= 10 )
  console.log('true')

See the Pen Fhqwr by John Tsevdos (@tsevdos) on CodePen.

As you can see CoffeeScript can be very expressive and in many cases you can write code that is as expressive as english! The well chosen aliases make the entire experience more fun and let you focus more on problem solving than on typos and missing curly braces.

If you like this article, stay tuned because the following CoffeeScript articles will be mind blowing…