Activate your free membership today | Log-in

Tuesday, December 23rd, 2008

Thomas Fuchs comes back with some JavaScript tips

Category: JavaScript

<>p>Thomas has been busy working on freckle, but has jumped back onto his blog again to give us some short tips:

Preventing console.log breakage

We have all been there. After a serious Firebug session, you forget to take out the console statements. Or, maybe you like to keep them in for the future. To be sure, you can redefine some no-ops:

JAVASCRIPT:
  1.  
  2. f(window['console'] === undefined)
  3.   window.console = { log: Prototype.emptyFunction };
  4.  

To not rely on Prototype, you can simply log: function() {}.

Kangax then shared his approach:

JAVASCRIPT:
  1.  
  2. (function(__global){
  3.   if (!__global.console || (__global.console && !__global.console.log)) {
  4.     __global.console = {
  5.       log: (__global.opera && __global.opera.postError)
  6.         ? __global.opera.postError
  7.         : function(){ }
  8.     }
  9.   }
  10. })(this);
  11.  

Staying DRY with some Curry

In this tip, Thomas talks about how he likes to use a little curry to reuse the same code in different ways.

For example, taking a generic page turner:

JAVASCRIPT:
  1.  
  2. // pages are numbered from 1 to 10
  3. var currentPage = 1, pageCount = 10;
  4.  
  5. function turnPage(dir){
  6.   currentPage += dir || 0;
  7.  
  8.   currentPage =
  9.     (currentPage == 0) ? pageCount :
  10.     (currentPage == pageCount+1) ? 1 : currentPage;
  11.  
  12.   // here we would do whatever is necessary to render
  13. }
  14.  

and currying some helpers:

JAVASCRIPT:
  1.  
  2. var nextPage = turnPage.curry(1),
  3.   previousPage = turnPage.curry(-1);
  4.  

Although the examples are using Prototype, other libraries have the equivalent curry power.

Related Content:

Posted by Dion Almaer at 6:57 am
3 Comments

++---
2.6 rating from 19 votes

3 Comments »

Comments feed TrackBack URI

Funny, I noticed this problem the other day and came up with a similar solution:

if(!console) conole = {log: function(){return false}}

Comment by Vezquex — December 23, 2008

SnoreFest2008 RoundUp Extreme++!!!

if i wanted javascript tips i’d go to javascript.about.com.

Comment by ilazarte — December 23, 2008

I avoid console.log(), typing that is cumbersome in the middle of a frenetic debugging session! Instead I use a log() facade.

function log() { if (console) console.log.apply(console, arguments); }

See http://jaybyjayfresh.com/2008/11/10/consolelog-in-safari-doesnt-apply-bad-safari/

Comment by Michael Mahemoff — December 23, 2008

Leave a comment

You must be logged in to post a comment.