Tuesday, December 23rd, 2008

Thomas Fuchs comes back with some JavaScript tips

Category: JavaScript

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. f(window['console'] === undefined)
  2.   window.console = { log: Prototype.emptyFunction };

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

Kangax then shared his approach:

javascript

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

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

and currying some helpers:

javascript

  1. var nextPage = turnPage.curry(1),
  2.   previousPage = turnPage.curry(-1);

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

Posted by Dion Almaer at 6:57 am
3 Comments

++---
2.7 rating from 24 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.