September  08

Bad ways to loop in JavaScript

Date: September 08, 2009. written by Prashanth Comments»

Hope you might have read my previous article Associate array are bad in Javascript, let me get in one step further beside associate array, what are the bad ways to loop a DOM, array, node list in JavaScript. Some of the Bad ways:

1. for (var i=0; i < arr.length; i++) {}
2. while (x = arr.pop()) {}
3. while (x = arr.pop()) {}
4. for (var i in arr) {} (this is the worst, remember JavaScript is not Python :p)
5. for (var i=0; arr[i]; i++) { var x = arr[i]; }
Better way:
for (var i=0, len=arr.length; i < len; i++) {}

Length of a HTML collection is expensive

Remember every DOM operation that you make is expensive so think of ways you can minimize. When are trying to do DOM operation like looping on a HTML collection with length its live during your looping user might make some change which might change the length of the collection. So, the better way is to avoid the length.

People are so used to JavaScript libraries and try to do array.item(i) rather than doing doing array[i], array[i] is like a hash value so its pretty fast, array.item(i) is a bad way.
for (var i=0, node; node = collection[i++];) {}

July  25

Firefox memory leak

Date: July 25, 2009. written by Prashanth Comments»

I am facing this strange memory leak problem when I open any of the google's heavy JavaScript application in firefox.


whenever i open gmail or google reader the memory usage of firefox goes up to 100%. But this doesn't happen either in safari or opera. Is firefox the culprit? Is anyone is facing this problem?

Ok Its not just me or the mac many of them are facing the same problem in almost all the operating systems.


http://www.codinghorror.com/blog/archives/000537.html
Bug Filed
Is Firebug doing this?

June  14

Node list is not array

Date: June 14, 2009. written by Prashanth Comments»

Node list is a collection of DOM Nodes. Most of them who code in Firebug tend to consider the node list as array because it looks like any other array. Node list has just two properties length and index. If you want to iterate on that you can use the old school way of incrementing the index or do any of the Enumerable functions by passing node list to call method. Let me show how to do that.

Example:
>>> foo = $$('div.post')
[div.post, div.post, div.post, div.post, div.post]
>>> Array.prototype.splice.call(foo)
>>> foo.each(function(item){console.log(item)})
<div class="post">
<div class="post">
<div class="post">
<div class="post">
<div class="post">
[div.post, div.post, div.post, div.post, div.post]

So what does call do? Call allows you to invoke a function as if it were a method of some other object. On above example foo is a node list its not a array but still I could able to splice that. ECMAScript specifies two methods call and apply. Both does relatively same job except the type of the argument. Apply takes a array as a argument.

May  20

Associate array are bad in JavaScript

Date: May 20, 2009. written by Prashanth Comments»

Associate array in javascript: An array is a linear allocation of memory in which elements are accessed by integers that are used to compute offsets. Arrays can be very fast data structures. Unfortunately, JavaScript does not have anything like this kind of array. Instead, JavaScript provides an object that has some array-like characteristics. It converts array subscripts into strings that are used to make properties.

>>foo = new Array()
>>foo[100] = 'bar'
>>foo.length
101

You can call foo as anything you like (Boolean, or Date, or String) all will work. It works because all you are doing is setting properties on an object in JavaScript foo['bar'] and foo.bar is one and same. When you iterate on the foo all you do is iterating on the properties. Remember all data type in JavaScript are object. Use array as a object and don't store key/value pairs.

>> foo['bar'] = 'buz'
>> foo['foobar'] = 'foobarbuz'
>> foo.length
0

May  20

starting javascript

Date: May 20, 2009. written by Prashanth Comments»

My law "When you don't know what you are doing sit back read and then code."

Most of the people start writing JavaScript without learning it( ridicules!). Like much of the language JavaScript also has good and bad parts. If you start doing something without learning it you will end up writing something non-standard or bad practices.

JavaScript despite having few bad parts its has some extra ordinary good parts which makes the language cool, beautiful, elegant, highly expressive language. So, to be a better programmer in JavaScript learn the good things, know the bad things and code the good things avoiding the bad part. Its very important to learn good things when you learn a language because its hard to unlearn the bad things.

Why JavaScript?

JavaScript is THE language of web browser, sun came up java applet gave a try to override JavaScript ended in a failure. Applet is just crap(You are a java lover you will find hard time reading my blog because I bash Java a lot :) and you thing java and JavaScript are one and the same I am gonna kick your ass get lost. Let me write about the name history behind JavaScript in a another post.). I call JavaScript as THE language because you don't have any other option. I see JavaScript is often blamed for browser hang probably because of you are doing extensive DOM operation. This is not the fault with JavaScript, DOM API very awful and JavaScript is unfairly blamed.

Good and Bad:

Good parts of JavaScript are loose typing, dynamic object, include functions and very bad part of JavaScript is using global variables. Some of the other good parts are lexical scoping, lambda(these is not unique, it resembles more of lisp). JavaScript is object oriented and class free. So inheritance happens between objects. Most of them who are from a strong typed languages feel bit hard to get used to it. People ask how would you identify a variable's type. I learned programming using Lisp, Python so I am much used to it and trust it is a good.

May  20

JavaScript comments

Date: May 20, 2009. written by Prashanth Comments»

JavaScript offers two form of comments:

  1. Block comments /* */
  2. Line ending comments //

Comments are pretty important for readability but obsolete comments are worse than no comments. The /* */ form of block comments came from a language called PL/I. PL/I chose those strange pairs as the symbols for comments because they were unlikely to occur in that language's programs, except perhaps in string literals. In JavaScript, those pairs can also occur in regular expression literals, so block comments are not safe for commenting out blocks of code.

/* var bar = 'baz'; var foo = 'foobar'.match(/\w*/g); alert(foo); */

In the above case the block comment close on the match which was not the intention. So better way is to do line ending comment(//).

May  19

Javascript in GNUEmacs

Date: May 19, 2009. written by Prashanth Comments»

Being a pro GNUEmacs user/activist :p whichever language I start with, first ever thing I would do is fix my emacs with the specific language mode. Since I would be writing more about ECMA/Javascript(of course python as well) it make more sense for me to start with the article about how to plug javascript mode in GNUEmacs.

There are few Emacs lisp files that you can plug in:

Personally I have used both, I find js2 mode cool, for those who are much concerned about indentation and spacing I would recommend to use js2-mode.

Now download the file from code.google.com and put that in your .emacs.d(this can be any foo folder but remember to set your home folder in your .emacs, .emacs.d is just the convention that I follow). Now paste the below lines in your .emacs , Byte compile the js2.el and your .emacs file and enjoy :)

(autoload 'js2-mode "js2" nil t)
(add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
(setq js2-use-font-lock-faces t)