
Ugly Variables and Encapsulation 

Ugly Variables In order to minimize that risk that a bookmarklet variable will collide with a variable already on the page (that is, will overwrite or reset a global variable that was set by the page author), it's wise to use variable names that are "ugly". The ugly variable is a a random string of upper and lowercase letters and numbers. (e.g.  c39Yt2U). There are 62 symbols that can be used in such a string. You can calculate the probability of collision between two randomly chosen ugly variables of the same length (a lower probability meaning a safer bookmarklet). If only one ugly variable is used then the probability is just 1 divided by the number of possibilities  as given in the table below.
We see that ugly variables of length 6 and above are extremely unlikely to collide with such a variable on another page; there are fewer than 1,000,000,000 pages currently on the web (according to some estimates for 1999.) Encapsulation You can sometimes encapsulate the script of a bookmarklet within a function and thereby reduce the number of global variables used to one. To do this for the 4.0 browsers, wrap a function around the script. That is,
For example, here is one way to write a bookmarklet which asks for some text and then alerts it back: javascript:V1=prompt('First name...','');V2=prompt('Last name...','');alert(V1 + V2) try it. As it stands, this bookmarklet is using two (ugly) variables (V1 and V2). We can reduce the number of variables to one by rewriting the script in the following way: javascript:V1={x:function(){var A=prompt('First name...','');var B=prompt('Last name...','');alert(A + ' ' + B)}};V1.x() try it The variables A and B are scoped to the function x(), and x() is scoped to the ugly object V1. If you are using many small variables in a bookmarklet you may be able to improve it by encapsulating it this way. Back to Javascript for Bookmarklets 