Another interesting technique I spotted in the gRaphaƫl code base is the use of a prefixed + used to cast a variable to a numeric type.

var data = [ undefined, null, 1, 10.2, new Date() ];
for (var i = 0, len = data.length; i < len; i++)
  console.log('cast %o: %o', data[i], +data[i]);

If you run this code, notice how casting undefined returns NaN which will ripple through your calculations. However, my favorite thing about this technique is how it handles Date objects. The following examples are equivalent.

var now = new Date();
console.log('now.valueOf: %o', now.valueOf());
console.log('+now: %o', +now);

Nice.

2 Comments

  1. Jake

    Can we get the output for those of us who are lazy and don’t want to run it ourselves?

  2. duncanbeevers

    var data = [ undefined, null, 1, 10.2, new Date() ];
    for (var i = 0, len = data.length; i < len; i++)
      console.log('cast %o: %o', data[i], +data[i]);
     
    cast undefined: NaN
    cast null: 0
    cast 1: 1
    cast 10.2: 10.2
    cast Thu Jan 21 2010 14:54:49 GMT-0800 (PST): 1264114489041

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.