Stop Javascript, use Coffeescript 2012-05-22

I write this blog since 2007, my first post (which I'm not too proud of after 5 years) was written on March 19, 2007. In those 5 years, a lot happened. Personally, I have burst periods when I write posts for 2 weeks then I disappear. On the web, there are two things that turned the javascript world upside-down :

  1. Node.js
  2. Coffeescript

Everyone agrees on the former, nobody agrees on the latter.

After years of javascript, I took the decision to go 99.9% coffeescript and avoid javascript as much as I can. Here are 3 to 5 reasons why I took this decision :

Coffeescript is idented

My first relationship with an indented language was with COBOL in 1998. I was deeply into Delphi/Pascal at this time this identation simply didn't make sense. The first time I wrote HTML, it wasn't indented. It didn't take long before I was completely lost in a maze of opening and closing tags.

So one day, I took the decision to always indent my files the same way, even if I had no obligation to. In fact, I think we all took that decision because I never see unindented languages being unindented. It would be suicide.

It ends up that I'm indenting my code anyway, why not leave out a couple of useless characters while I'm it?

Arrows

I pretty much hate the word function because it's long to write and it's plastered everywhere the moment you begin to write well structured javascript. Arrows are shorter and combined with indentation, you transform a callback

in

We are writing code, not emoticons

I'm talking about ; , ( ) { } :. This kind of stuff should only be used to write emoticons.

transforms to

Shortcuts

You want to execute a function only if it is not null and is actually a function? In classic javascript, I have to think about it but I would do something like :

I would have to test it somewhere to make sure that typeof returns function and not Function (capitalized). Let's forget about this ugly code and write :

This is just an example, learn coffeescript to know more.

String interpolation

Really? I have to use +? I even used arrays to make it clearer not too long ago :

Let's add some decency :

Ashkenas (creator of coffeescript) is my brother

I met MACournoyer 2-3 times. He is the guy who wrote the best book about creating a programming language. This incredible book inspired Ashkenas to create coffeescript. As you can see, we have a very close relationship, he is literally like a brother to me!


How to write javascript code to fit in lines of 80 chars 2012-04-30

I recently read Code Conventions for the JavaScript Programming Language from Douglas Crockford, the guy that discovered JSON. I was really surprised to see such an old convention as Avoid lines longer than 80 characters. For the past years, I didn't follow this convention until a couple of months ago when I accidentally clicked the option to show the 80 chars limit on gEdit and didn't bother to unclick it. Without noticing it, I began writing with a limit of 80 chars and it made my code much clearer. Plus, nobody likes to scroll horizontally, even programmers.

Functions

This one is simple. You should just avoid having a long list of arguments by putting them on 2 lines with a tab (or 2 spaces) on the second line.

Use hashes for optional arguments

A good way of avoiding long list of argument is to put optional arguments in a hash. Suppose that the first two arguments are required and the other ones are optional. You could write something like this.

Chains

In jQuery, we often have to write a long chain of command. Here is how I write it to make it clearer.

One-liner IF

The more I code, the less lines of code I want. I write a lot of Ruby and I like one-liners. Here's a little tip on one-liners ifs in javascript.

Tabs are dead, use 2 spaces

When I was a brand new programmer, tabs were all the rage. The bigger your tab space, the better. I was using a 8 spaces tab length at the time. And those were hardcore tabs too, not pseudo-tabs created by adding spaces one after the other. The best programmers were even uselessly indenting some statements as in this :

These days, most editors have the “Insert spaces instead of tabs” and “Tab width” options. Look for them and do the following : 1. Check the box beside the “Insert spaces instead of tabs” 2. Write “2” inside the “Tab width”


How to make sure undefined is not defined 2011-09-13

Think about it, you write a plugin or a library (let's name it jsKata) and your code contains checks to see if certain things are undefined.

Here's an example :

if (obj.name === undefined) {
  obj.name = "This object has no name";
}

This code works well until you include another script (found on an obscure website) and it breaks your previous code. By debugging the code, you see the value of undefined is no more undefined but false.

Yes, I know that you thought it was impossible to define undefined but it is, you just have to write undefined = false.

Redefine undefined

There's two way of redefining undefined and they both use self-invoking functions.

Method 1 : Scope your code

(function(undefined) {
  /* your complete code here */
})();

As you see, the self-invoking function has one parameter named undefined. At line 3, the self-invoking functions is called without any parameter. It results that the parameter has the value undefined (or it is defined to undefined if you prefer).

Take a look at this javascript :

It will display false and then display undefined even if undefined was globally defined at first.

This is the HTML that goes with it :

You can also execute it here.

Method 2 : Globally redefine undefined

There's another method but I don't like it that much. It redefines undefined but nothing protects it from being badly redefined in another chunk of code.

undefined is a global variable accessible using the global window object. Line 2 defines undefined and line 3 display the value of undefined as false. On line 4, I use a self-invoking function as method 1 does but now, I define the global undefined variable through the global window object.

The HTML of this example :

You can also execute it on jsFiddle.

Other methods

Some commentors pointed me other ways of doing it.

You can use typeof :

typeof undefined == "undefined"

Or you could use void(0), it always returns undefined

undefined === void(0) // this returns true


Creating namespaces with self-invoking functions 2011-09-05

When a project's javascript grows, it can be easy to lose ourselves, buried under thousands of lines of js code. That's why I like to create namespaces to keep everything together.

Let's say I have functions to work with cats and I create a namespace for it because there are lots of other functions related to dogs.

As you see, to access the cat list I must use the complete name including the namespaces like this : Animal.Cat.list. You can guess that it will get pretty long as the code grows.

Let's make this call shorter.

Now, I only have to write c.list because c is an alias of the Animal.Cat namespace. Thanks to self-invocation!

You probably noticed that the code is longer but this is just an example. In a real situation, this technique would make your code much clearer.

Don't forget to subscribe to my newsletter!


Self-invoking functions explained line by line 2011-08-22

I never knew it was possible to love a syntax but since, I fell in love with the self-invoking function which can be summarized like this : (function(){})(). Yes this is a valid syntax though it doesn't do much in this form (it creates a function that does nothing and call it).

Some people call it self-invocation or self-executing but I don't think it has an official name.

Let’s break it down

It will become clearer if I execute some code and write it on more than one line :

( 
  function() {
    console.log("this line is called");
  }
)
();

Line 1 : ( This first parenthesis is used as grouping operator. Read more here and here.

Line 2 : function() { This create an anonymous function. I could write something like function doSomething() { but in the case of a self-invoking function, this is useless because the function is in its own little scope (line 1) and can't be called from outside of it.

Line 3 : console.log(“this line is called”); This is the code that will be invoked.

Line 4 : } This clauses the function opened at line 2.

Line 5 : ) Clauses the parens opened at line 1.

Line 6 : (); We call the function created at line 2 and returned within the scope from line 1 to 4.

Let's write it in a more compact syntax :

(function() {
  console.log("this line is called");
})()

See my post about using self-invoking functions to create namespaces.

Don't forget to subscribe to my newsletter!