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.

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…

CoffeeScript gotchas (part 1): Comments, strings, booleans, arrays and functions

In the last couple of months I took some time to learn and work on a CoffeeScript project. Writing CoffeeScript is a lot of fun, and if you know plain Javascript you already know most of the Coffeescript syntax – just start removing all the syntax cluttering like semicolons, parenthesis and square brackets and suddenly you are writing Coffeescript!

The really cool stuff begins when you dig a bit more into the language. There’s some nice demonstrations of features that I had to learn the hard way.

Before jumping into these, have a look at the well-written, free on-line book Coffeescript Cookbook. This excellent resource saved me a lot of time in many situations.

Comments

You can have single-line and multi-line comments in CoffeeScript. Always keep in mind that during compilation, the compiler will completely ignore the single line comments (they wont appear in your final Javascript file) but will keep the multi-line comments intact. In the Codepen examples below you can click the “view compiled” link to see the generated JS code and the result tab to see the result (if any)…

# Single-line comment
###
Multiline comment
###

See the Pen CoffeeScript gotchas (part 1): Comments by John Tsevdos (@tsevdos) on CodePen.

String Interpolation

Probably the best feature Coffeescript provides! You can finally do things like this:

name = "John"
greeting1 = "Hello, #{name}!" # -> Hello, John!
greeting2 = 'Hello, #{name}!' # -> Hello, #{name}!

document.write greeting1
document.write '
'
document.write greeting2 

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Keep in mind that double quotes are needed to compile correctly. You can even use functions!

mrFunc = (name) -> "Mr. " + name
message = "Hello, #{mrFunc 'John'}"

document.write message

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Heredoc (multiline strings)

You can also use Heredocs. They even support interpolation!

multiline = """
This is 
a multiline
string
of #{3+2}
lines
"""


document.write multiline

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Booleans

Not much news here, apart from some syntax goodies… You can use true with two more keywords, yes and on and you can use false with the opposites, no and off. Sometimes it makes more sense to use these keywords instead of the normal true/false.

# true === yes === on
if true
  document.write 'true
'
  
if yes
  document.write 'yes
'

if on
  document.write 'on

'

# false === no === off
if !false
  document.write 'false
'
  
if !no
  document.write 'no
'

if !off
  document.write 'off
'

See the Pen CoffeeScript gotchas (part 1): Booleans by John Tsevdos (@tsevdos) on CodePen.

Arrays

CoffeeScript allows a very convenient syntax to create specific array ranges. You can create any range using the two dots syntax (inclusive range, which simply means that it will include the last value). Adding three dots instead excludes the last value (exclusive range). Finally you can use reverse ranges the same way. Have a look at the examples, they are much easier than they sound…

range1  = [0..10]  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range2  = [0...10] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range20 = [20..0]  # [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

See the Pen CoffeeScript gotchas (part 1): Arrays by John Tsevdos (@tsevdos) on CodePen.

Functions default values

One of the coolest and most usable CoffeeScript features is the default values on functions. Instead of checking if a value exists, etc. you can simply apply the default value right next to the parameter.

greeting = (name = "friend") -> 
  "Hello #{name}"

document.write greeting('John')
document.write '<br />'
document.write greeting()

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

IIFE – Immediately Invoked Function Expressions

Another tricky part when start to learn CoffeeScript is how you write an IIFE. The syntax is a bit tricky, so have a look below (keep in mind that only CoffeeScript 1.3 and above supports default values on IIFE).

do (doc = document, jQuery = $) -> 
  document.write "IIFE magic"

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

Stay tuned for more CoffeeScript ;-)

Gulp boilerplate for web designers

Two weeks ago, I published a Grunt.js boilerplate with common tasks for web designers. This week I’m trying out the new kid on the block, gulp. Gulp is also a node-based task manager, but it works a bit different than Grunt. It works with streams and pipes, making it very fast and easy to understand. I strongly recommend you have a look at this eye-opening presentation on gulp to better understand how it works and why it’s here to stay.

My gulp boilerplate has more or less the same features as my Grunt boilerplate. To mention a few :

If you want to learn more about how gulp works, feel free to have a look at the repository. Also if you have any recommendations or comments feel free to pull, fork, star etc. ;-)

Grunt boilerplate for web designers

Hi all, I’m very happy to announce my first grunt project that will definitely help you if you are a web designer. What I tried to accomplish was to build a grunt task list that will provide much of the CodeKit functionality and convenience by running simple grunt tasks (commands). Some of the features the grunt tasks provide are listed below:

  • SMACSS (Scalable and Modular Architecture for CSS) ready infrastructure
  • Compile Sass files
  • Compass and Burbon support
  • JsLinter
  • CSS, JS and HTML minification
  • Image optimization
  • Live-reload

Have a look at the official repository and don’t hesitate to contact me for any suggestions/thoughts. More details on how to use it will be provided on an upcoming screencast (stay tuned). Also feel free to contribute, fork, star etc ;-)

My sublime text plugin list

Sublime text is my text editor of choice for many reasons. It’s super fast and responsive, it’s available for many OS (I use it in both Linux and Windows) and finally it has plugins (packages) for everything! Many colleagues ask me what packages I use, well below you can view the sublime text packages I’m using.

Developer Tools and Console tips

You can save a huge amount of time simply by learning to use the development tools (all modern browsers have them). Below I’m demonstrating some nice tricks that I’m sure will help you. Keep in mind that the browser I use for development is Chrome (Chromium to be precise), so some tips might not work if you use the dev tools of another browser.

Select element(s) without jQuery

You can select any element by using the dollar sign selector ($('a') ) even if you don’t have jQuery available on the document! This convention is using the document.querySelector under the hood (for example document.querySelector('a')), so it returns only the first matched element.

If you want to select multiple elements you can use the double dollar sign selector ( $$(‘a’) ) which returns an array of matched elements. The specific convention is using the document.querySelectorAll (for example document.querySelectorAll('a')).

Keep in mind that you can use any valid selectors like #ids, .classes, etc., depending your browser’s CSS selectors capabilities.

Console.log objects

It’s a bit frustrating when you try to log an object, only to get the already useless output [object Object]. Well, try using a comma (,) instead of the plus sign (+). You can also log multiple items if you like…

Console.log the event listeners of an element

This function will save you tons of working hours! Just pass the element you want to check at the getEventListeners() function, and voila, the console logs all the events of the element.

Monitor every single event fired on an element

A very similar method that logs every single event triggered is the monitorEvents() function. It works just like the above function, simply pass the element you want to track and you are ready to go! If this function is driving you crazy (as I explained, it logs everything), you can limit the events you log by passing a string or an array of strings with the events you want to log. Don’t forget to run the unmonitorEvents() function to stop the logging otherwise the browser will continue logging your events!

Log arrays in beautiful tables using the console.table

If you want to log arrays in a more beautiful and useful way, then simply try the console.table() function.

Log all properties of an element

By passing an element to the dir() function you can log all the properties of that element (identical to the view that you would see in the DOM panel).

How to add iPhone/iPad startup images (splashscreens)

We’ve seen how you can add custom touch icons for iPhone/iPad use (if you need more information have a look at Mathias Bynens excellent article on this topic) but did you know that you can add custom start-up images (aka splash screens)? Well you can and it’s very easy, just prepare your images (for various resolutions, retina displays etc, that’s the tough part) and use the below markup to include them. A very easy way to polish your web app and impress your mobile/tablet visitors.

Ambrosia “speaks” French, Serbian and Romanian

I just wanted to dedicate this post to the generous translators of the Ambrosia theme. The theme made it to version 1.1.5 and although I maintain it (making sure it works with every new WordPress version), some people are providing valuable support by contributing their translations. So far the theme is available in English, French (Nicolas Rouichi), Serbian (Andrijana Nikolic) and Romanian (Alexander Ovsov). So if you want your name to appear at the theme’s official page and repository, you know what you have to do ;-)

Get element’s tagname using DOM’s tagName property

A couple of weeks ago I posted how can you get an element’s tagname using jQuery’s .prop() method. A simpler alternative could be the below code :

See the Pen Get element’s tagname using DOM’s tagName property by John Tsevdos (@tsevdos) on CodePen

The .get() method (don’t confuse this method with the jQuery’s AJAX .get(), they are completely different) retrieves the DOM element and then we simply get it’s tagName property (and convert it to lowercase). We can even retrieve the DOM element from a jQuery array using the below syntax (without the .get() method) and have the exact same result.

See the Pen Get element’s tagname using DOM’s tagName property by John Tsevdos (@tsevdos) on CodePen

I believe that the above method is easier and faster than the previous one.

Moved all my code to CodPen

Once again (and hopefully for the last time) I moved all my code snippets to Codepen. I think it better suits my needs since most of my code examples are front end related and Codepen has a tremendous advantage there, because it allows you to publish full HTML, CSS and JS solutions and see the final output instantly! The social features it provides are also impressive, you can fork a “pen”, play with it, republish it etc, and finally it looks really good (excellent choice of color palette) and it’s very customisable.

You can view my profile and play with my pens, don’t forget to follow me ;-) My gist list will remain and I’ll continue posting there as well, but mostly only server side code such as PHP scripts.