Quantcast
Channel: machine501
Viewing all articles
Browse latest Browse all 2

console.log in CoffeeScript

$
0
0

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

1 2
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:

1 2 3 4 5 6 7
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.

1 2 3 4
root = exports ? this
 
if typeof(root.console) is "undefined"
root.console = { log: () -> }

Outputs:

1 2 3 4 5 6 7 8 9 10 11
(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.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images