console.log in CoffeeScript

You always do this in JavaScript to make sure your console statements don’t blow up on IE when the console is not open.

if typeof(console) is "undefined"
   console = { log: () -> }

But you’ll just end up with no console on any of the browsers that support the console because this is what gets output as JavaScript:

var console; // <-- doh!

if (typeof console === "undefined") {
  console = {
    log: function() {}
  };
}

view raw attempt.js This Gist brought to you by GitHub.

What happened was that the variable console was defined in the local scope and that’s what you’re setting when you assign the value.  And that’s what gets used for the rest of the definition.  The fix is to make sure to attach it to the global object, whatever that is given the context.

root = exports ? this

if typeof(root.console) is "undefined"
  root.console = { log: () -> }

Outputs:

(function() {
  var root; // yay
  // some other junk here
  if (typeof root.console === "undefined") {
    root.console = {
       log: function() {}
    }
  }

  // the rest
)
view raw attempt2.js This Gist brought to you by GitHub.

Or you could just do:

console?.log "foo"

But the exercise illustrates how you often have to think about the JS output until you manage to internalize it.

Tagged ,

Hello world! … Again

I stopped blogging.  I switched servers.  I was heads down on a really hard project.

But now I’m back and I’ll be talking about new web and mobile goodness.

Tagged