Ask HN: What is your favorite Javascript code snippet?

6 points by donohoe ↗ HN
Any useful gems or ways to overcome common hurdles? Would love to see and compare insights. Preferably framework/library agnostic if possible.

6 comments

[ 2.7 ms ] story [ 23.1 ms ] thread
for (var a=0, len = arr.length; a < len; a++) { // looping for speed, cache the length and save an access }
I'm partial to keeping a "bind" function handy. (Function#bind will be in ECMAScript 5, but it's not quite here yet). It's crucial for keeping your sanity when trying to use "this" with callbacks, Ajax, or async.

    var bind = function(func, context) {
      var slice = Array.prototype.slice;
      var args  = slice.call(args, 2);
      return function() {
        return func.apply(context || {}, args.concat(slice.call(arguments)));
      };
    };
for (var i=0, node; node=parentElem.childNodes.item(i); i++) { // iterates over an element's child nodes; 2nd statement in for loop returns undefined when out of items }
Some of these assume you have Firebug or similar for console output.

Quick and easy browser sniff:

  var browser = (function x(){})[-5]=='x' 
               ? 'ff3' : (function x(){})[-6]=='x' 
               ? 'ff2' : /a/[-1]=='a' 
               ? 'ff'  : '\v'=='v' 
               ? 'ie'  : /a/.__proto__=='//' 
               ? 'safari' : /s/.test(/a/.toString) 
               ? 'chrome' : /^function \(/.test([].sort) 
               ? 'opera'  : 'Unknown';
Round to Nearest Multiple

  var roundThis = 54;
  var closest = Math.round(parseInt(roundThis)/20)*20;
  // output = 60
URL Paramaters

  var parts  = window.location.search.substr(1).split("&");
  var params = {};
  for (var i = 0; i < parts.length; i++) {
      var temp = parts[i].split("=");
      params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
  }
  console.log(params);
URL Hash Paramaters

  console.log(window.location.hash.substr(1).split("&"));