10 Small Things You May Not Know About Javascript

7:27:00 PM 0 Comments

t doesn't matter how many years I've been dealing with Javascript – it contains many little things that surprises me almost every week. For me, Javascript means a constant learning process.

In this article, I'll provide ten small Javascript tips, mainly aimed for beginner and intermediate Javascript developers. Hopefully there's at least one useful tip for every reader :).

1. Variables conversions

This sounds quite obvious, but as far I've seen, using object constructors, like Array()or Number() for converting variables is quite common practice.

Always use primitive data types (sometimes referred as literals) for converting variables. These won't do any extra tricks and they usually have better performance.

  1. var myVar   = "3.14159",  
  2.     str     = ""+ myVar,//  to string  
  3.     int     = ~~myVar,  //  to integer  
  4.     float   = 1*myVar,  //  to float  
  5.     bool    = !!myVar,  /*  to boolean - any string with length 
  6.                             and any number except 0 are true */  
  7.     array   = [myVar];  //  to array  

Converting to dates (new Date(myVar)) and regular expressions (new RegExp(myVar)) must be done with constructors. However, always use /pattern/flags when creating regular expressions.

2. Converting decimals to hex or octals and vice versa

Are you writing separate functions for hex (or octal) conversios? Stop. This can be easily done with existing methods:

  1. (int).toString(16); // converts int to hex, eg 12 => "C"  
  2. (int).toString(8);  // converts int to octal, eg. 12 => "14"  
  3. parseInt(string, 16) // converts hex to int, eg. "FF" => 255  
  4. parseInt(string, 8) // converts octal to int, eg. "20" => 16  

3. More playing with numbers

In addition to previous section, here are some more small tricks with when dealing with numbers.

  1. 0xFF; // Hex declaration, returns 255  
  2. 020; // Octal declaration, returns 16  
  3. 1e3; // Exponential, same as 1 * Math.pow(10,3), returns 1000  
  4. (1000).toExponential(); // Opposite with previous, returns 1e3  
  5. (3.1415).toFixed(3); // Rounding the number, returns "3.142"  

4. Javascript Version Detection

Are you aware which version of Javascript your browser supports? If not, checkJavascript Versions sheet from Wikipedia.

For some reason, features in Javascript version 1.7 are not widely supported. However, most browsers released within a year support features in version 1.8 (and in 1.8.1).

Note: all the versions of Internet Explorer (8 and older) supports only Javascript version 1.5.

Here's a tiny script both for detecting the version of Javascript via feature detection. It also allows checking support for specific version of Javascript:

  1. var JS_ver  = [];  
  2.   
  3. (Number.prototype.toFixed)?JS_ver.push("1.5"):false;  
  4. ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;  
  5. ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;  
  6. ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;  
  7. ("".trimLeft)?JS_ver.push("1.8.1"):false;  
  8.   
  9. JS_ver.supports = function()  
  10. {  
  11.     if (arguments[0])  
  12.         return (!!~this.join().indexOf(arguments[0] +",") +",");  
  13.     else  
  14.         return (this[this.length-1]);  
  15. }  
  16.   
  17. alert("Latest Javascript version supported: "+ JS_ver.supports());  
  18. alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));  

5. window.name for simple session handling

This one is something I really like. You can assign values as a string for window.nameproperty and it preserves the values until you close the tab or window.

Although I'm not providing any script, I strongly suggest you to take full advantage from it. For instance, it's very useful for toggling between debugging and (perfomance) testing modes, when building a website or an application.

6. Testing existence of property

This issue can be approached at least from two directions. Either we check whether property exists or we check the type of property. But always avoid these small mistakes:

  1. // BAD: This will cause an error in code when foo is undefined  
  2. if (foo) {  
  3.     doSomething();  
  4. }   
  5.   
  6. // GOOD: This doesn't cause any errors. However, even when  
  7. // foo is set to NULL or false, the condition validates as true  
  8. if (typeof foo != "undefined") {  
  9.     doSomething();  
  10. }  
  11.   
  12. // BETTER: This doesn't cause any errors and in addition  
  13. // values NULL or false won't validate as true  
  14. if (window.foo) {  
  15.     doSomething();  
  16. }  

However, there may be situations, when we have deeper structure and proper checking would look like this:

  1. // UGLY: we have to proof existence of every  
  2. // object before we can be sure property actually exists  
  3. if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {  
  4.     doSomething();  
  5. }  

7. Passing arguments for function

When function has both required and optional parameters (arguments), eventually we may end up with functions and function calls looking like this:

  1. function doSomething(arg0, arg1, arg2, arg3, arg4) {  
  2. ...  
  3. }  
  4.   
  5. doSomething('''foo', 5, [], false);  

It's always easier to pass only one object instead of several arguments:

  1. function doSomething() {  
  2.     // Leaves the function if nothing is passed  
  3.     if (!arguments[0]) {  
  4.         return false;  
  5.     }  
  6.   
  7.     var oArgs   = arguments[0]  
  8.         arg0    = oArgs.arg0 || "",  
  9.         arg1    = oArgs.arg1 || "",  
  10.         arg2    = oArgs.arg2 || 0,  
  11.         arg3    = oArgs.arg3 || [],  
  12.         arg4    = oArgs.arg4 || false;  
  13. }  
  14.   
  15. doSomething({  
  16.     arg1    : "foo",  
  17.     arg2    : 5,  
  18.     arg4    : false  
  19. });  

This is only a rough example of passing an object as an argument. For instance, we could declare an object with name of the variable as keys and default values as properties (and/or data types).

8. Using document.createDocumentFragment()

You may need to dynamically append multiple elements into document. However, appending them directly into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you should use document fragments, which are appended only once after completion:

  1. function createList() {  
  2.     var aLI = ["first item""second item""third item",  
  3.         "fourth item""fith item"];  
  4.   
  5.     // Creates the fragment  
  6.     var oFrag   = document.createDocumentFragment();  
  7.   
  8.     while (aLI.length) {  
  9.         var oLI = document.createElement("li");  
  10.   
  11.         // Removes the first item from array and appends it  
  12.         // as a text node to LI element  
  13.         oLI.appendChild(document.createTextNode(aLI.shift()));  
  14.         oFrag.appendChild(oLI);  
  15.     }  
  16.   
  17.     document.getElementById('myUL').appendChild(oFrag);  
  18. }  

9. Passing a function for replace() method

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this would be passing a separate function for method String.replace().

Following example is a rough implementation of making a more verbose output from a single deal in online poker:

  1. var sFlop   = "Flop: [Ah] [Ks] [7c]";  
  2. var aValues = {"A":"Ace","K":"King",7:"Seven"};  
  3. var aSuits  = {"h":"Hearts","s":"Spades",  
  4.             "d":"Diamonds","c":"Clubs"};  
  5.   
  6. sFlop   = sFlop.replace(/\[\w+\]/gi, function(match) {  
  7.     match   = match.replace(match[2], aSuits[match[2]]);  
  8.     match   = match.replace(match[1], aValues[match[1]] +" of ");  
  9.   
  10.     return match;  
  11. });  
  12.   
  13. // string sFlop now contains:  
  14. // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  

10. Labeling of loops (iterations)

Sometimes, you may have iterations inside iterations and you may want to exit between looping. This can be done by labeling:

  1. outerloop:  
  2. for (var iI=0;iI<5;iI++) {  
  3.     if (somethingIsTrue()) {  
  4.         // Breaks the outer loop iteration  
  5.         break outerloop;  
  6.     }  
  7.   
  8.     innerloop:  
  9.     for (var iA=0;iA<5;iA++) {  
  10.         if (somethingElseIsTrue()) {  
  11.             // Breaks the inner loop iteration  
  12.             break innerloop;  
  13.         }  
  14.   
  15.     }  
  16. }  

Afterwords

Go ahead and comment! Did you learn anything new? Do you have good tips to share? I'm always delighted for sharing information about all the little details in Javascript.

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.