Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
JavaScript Tips (aymanh.com)
79 points by RBerenguel on May 6, 2010 | hide | past | favorite | 23 comments


The array.join vs. string concat tip is bogus. Might have been true some years ago, but joining an array is only marginally faster in Firefox and even slower in Chrome than concatenating strings:

http://www.phoboslab.org/crap/jsarrayconcat.html


Good to know. I've been reflexively doing that for many years now, and wasn't aware that JS implementations had finally optimized around it.


Be very careful to not call console.log in any released code, or you'll have a very interesting time trying to figure out why your app works for exactly you and no-one else.


I usually put a safety check at the top of my code, ensuring that console and console.log exist (and, if they don't, defining something appropriate in their place).


  if (!window.console) {
    window.console = {
      log:function(){},
      debug:function(){},
      trace:function(){}
    };
  }


I just use:

    if ( errror ) {
        try { console.error(msg); }
        catch(e) {};
    }
Of course I do all of my debugging in Firefox with Firebug, and my goal is to ensure that these errors don't happen in production code so other browsers never hit the try/catch block. In rare cases where an error only happens in IE, I can throw an alert into the catch.


Its terrible practice to catch an error and do nothing with it.


Generally yes, I agree. But in this case all I'm doing with the error is displaying it to the programmer, and it doesn't matter to me if the programmer has to be using Firefox to see it. We were talking about displaying debugging messages and dealing with a missing console, not handling application failures.


I stumbled upon a few of the mentioned tricks in the article lately, while working on JavaScript projects in my spare time.

Another little trick that I personally like because of its simplicity is the following:

  Array.prototype.clear = function(){this.length=0;}
Clears an Array the easy way.


You just need to be aware that this might cause unexpected behavior when using for ... in

  Array.prototype.clear = function() {this.length = 0};
  var a = [1,2,3];
  var s = "";
  for(var i in a) s += i +",";
  alert(s);//1,2,3,clear
(not that many people use it this way, but since we're on the topic of little known tricks about js, I think it's worth mentioning)


The binary tree example is fine for very small and completely balanced trees, but for anything else you're going to get a lot of undefined entries in the array. There's no need for this; the array elements can be data structures like:

   { 'data': data, 'left': null, 'right': null }
When you insert a new child, you can just push it onto the end of the array, find its parent by comparing the 'data' values, and set the parent's 'left' or 'right' to point to the child's index in the array. Update the child's 'left' or 'right' as needed if the child isn't a leaf.

He mentions that you can build a traditional binary tree out of objects, but he makes it sound a lot more complicated than it actually is. His implementation of a binary tree breaks down at a scale where it's probably simpler and nearly as fast to just use an associative array and linear traversal, and he still requires writing the insertion, removal, and traversal methods.


In JavaScript, Arrays are not actually arrays. They're not a contiguous block of memory. They're just Objects (i.e. hash tables) that key on integers.

If you look at the indices it will look like you have a bunch of undefined elements in the array, but no memory has actually been consumed for those indices in the array so nothing is wasted.


Excellent point. I forget that javascript doesn't really have arrays, just array syntax. My example is much more appropriate in other languages with true arrays and the ability to store object references in them.


In most modern browsers Array.join and += are about equal in performance for most use cases. Depending on the length of the strings and/or the number of segments joined - performance varies. Wouldn't worry too much about it.


Agreed. I just tested performance and the difference was moot. I'd say += is easier to read so unless you're doing something really heavy duty with strings I wouldn't worry.


Of course, data should be sorted server-side if possible, so this shouldn't be used unless absolutely necessary

I understand that this is 2006 article. but this is not sound advise today. It is fine for the service (server) to order data, but one should not rely on the fact that the service will do so as many times reordering data is a function of the display (view).


The article is from 2006. You may well know the tips.


Plus the language hardly changed in the 10 years before that.


True in theory but not in practice: jQuery changed a lot of typical JavaScript usage patterns.


js is getting interesting with projects like nodejs (Heruko support), expressjs, cappuccino and sproutcore... Plus HP/Palm WebOS apps are HTML/CSS/JS, OSX widgets, Chrome extensions, factor in HTML5, js in mongodb and couchdb, and one starts to realize the gains to be made to the dev process by being a js guru for client and server.


    var queue = [];
    queue.add = queue.push;
    queue.remove = queue.shift;
Oh god no! I pray I don't ever have to work with this guy after he learns about prototypes.

Also, he is using "shift" and requires binary trees, but makes no mention whatsoever of the performance characteristics?


Yawn. These are hardly JavaScript-specific programming tips, except the Firebug ones. You can easily build a stack or queue on top of arrays in any language, and common subexpression elimination helps in other dynamic languages as well.


The comments on this article are like YouTube comments of programming.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: