Ten amazing JavaScript skills

Source: Internet
Author: User
Although I have been using Javascript for development for many years, it often has some small features that surprise me.

It doesn't matter how many years I 've been dealing with Javascript-it contains into 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 :).

Although I have been using Javascript for development for many years, it often has some small features that surprised me. For me, Javascript requires continuous learning. In this article, I will list 10 tips for using Javascript, mainly for beginners and intermediate developers of Javascript. I hope every reader can learn at least one useful technique.

1. Variables conversions variable Conversion

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.

It looks simple, but as I can see, using constructors such as Array () or Number () for variable conversion is a common practice. Always use the original data type (sometimes called the literal volume) to convert the variable, which is more efficient without any additional impact.

var myVar   = "3.14159",      str     = ""+ myVar,//  to string      int     = ~~myVar,  //  to integer      float   = 1*myVar,  //  to float      bool    = !!myVar,  /*  to boolean - any string with length                             and any number except 0 are true */      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.

The new Date (myVar) and regular expression (new RegExp (myVar) must use constructors and use the/pattern/flags format when creating regular expressions.

2. Converting decimals to hex or octals and vice versa decimal conversion to hexadecimal or octal, or vice versa

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

Do you want to write a separate function to convert hexadecimal (or octal? Stop now! There are more easily available functions to use:

(int).toString(16); // converts int to hex, eg 12 => "C"  (int).toString(8);  // converts int to octal, eg. 12 => "14"  parseInt(string, 16) // converts hex to int, eg. "FF" => 255  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.

In addition to the previous section, there are more techniques to process numbers.

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

Are you aware which version of Javascript your browser supports? If not, check Javascript 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 of 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:

Do you know which version of Javascript your browser supports? If you do not know, go to Wikipedia to check the Javascript version table. For some reason, some features of Javascript 1.7 are not widely supported. However, most browsers support the features of version 1.8 and 1.8.1. (Note: All ie browsers (IE8 or older versions) only support Javascript of version 1.5.) Here is a script that can detect the JavaScript version by detecting features, it can also check the features supported by specific Javascript versions.

var JS_ver  = [];    (Number.prototype.toFixed)?JS_ver.push("1.5"):false;  ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;  ((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;  ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;  ("".trimLeft)?JS_ver.push("1.8.1"):false;    JS_ver.supports = function()  {      if (arguments[0])          return (!!~this.join().indexOf(arguments[0] +",") +",");      else          return (this[this.length-1]);  }    alert("Latest Javascript version supported: "+ JS_ver.supports());  alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));  
5. window. name for simple session handling uses window. name for simple session Processing

This one is something I really like. You can assign values as a string for window. name property 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.

This is what I really like. You can specify a string as the value of the window. name attribute until you close the tag or window. Although I have not provided any scripts, I strongly recommend that you make full use of this method. For example, switching between debugging and testing modes is very useful when building a website or application.

6. Testing existence of property determines whether the property exists

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

This issue involves two aspects: Checking attributes and obtaining attribute types. However, we always ignore these small things:

// BAD: This will cause an error in code when foo is undefined  if (foo) {      doSomething();  }     // GOOD: This doesn't cause any errors. However, even when  // foo is set to NULL or false, the condition validates as true  if (typeof foo != "undefined") {      doSomething();  }    // BETTER: This doesn't cause any errors and in addition  // values NULL or false won't validate as true  if (window.foo) {      doSomething();  }  

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

However, in some cases, when we have a deeper structure and need a more appropriate check, we can do this:

// UGLY: we have to proof existence of every  // object before we can be sure property actually exists  if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {      doSomething();  }  
7. Passing arguments for function to pass parameters to the function

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

When a function has both required and optional parameters, we may do this:

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

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

Passing an object is always easier than passing a bunch of parameters:

function doSomething() {      // Leaves the function if nothing is passed      if (!arguments[0]) {          return false;      }        var oArgs   = arguments[0]          arg0    = oArgs.arg0 || "",          arg1    = oArgs.arg1 || "",          arg2    = oArgs.arg2 || 0,          arg3    = oArgs.arg3 || [],          arg4    = oArgs.arg4 || false;  }    doSomething({      arg1    : "foo",      arg2    : 5,      arg4    : false  });  

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

This is just a simple example of passing an object as a parameter. For example, we can declare an object, the variable name as the Key, and the default Value as the Value.

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 shocould use document fragments, which are appended only once after completion:

You may need to dynamically append multiple elements to the document. However, inserting them directly into the document will cause this document to be re-deployed each time. On the contrary, you should use the document fragments and add them only once after they are built:

function createList() {      var aLI = ["first item", "second item", "third item",          "fourth item", "fith item"];        // Creates the fragment      var oFrag   = document.createDocumentFragment();        while (aLI.length) {          var oLI = document.createElement("li");            // Removes the first item from array and appends it          // as a text node to LI element          oLI.appendChild(document.createTextNode(aLI.shift()));          oFrag.appendChild(oLI);      }        document.getElementById('myUL').appendChild(oFrag);  }  
9. Passing a function for replace () method is used to pass a function

There are situations when you want to replace specific parts of the string with specific values. The best way of doing this wocould 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:

Sometimes you want to replace a part of the String with other values. The best way is to pass an independent function to String. replace. The following is a simple example of achieving massive output in online poker games:

var sFlop   = "Flop: [Ah] [Ks] [7c]";  var aValues = {"A":"Ace","K":"King",7:"Seven"};  var aSuits  = {"h":"Hearts","s":"Spades",              "d":"Diamonds","c":"Clubs"};    sFlop   = sFlop.replace(/\[\w+\]/gi, function(match) {      match   = match.replace(match[2], aSuits[match[2]]);      match   = match.replace(match[1], aValues[match[1]] +" of ");        return match;  });    // string sFlop now contains:  // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  
10. label usage in the Labeling of loops (iterations) loop

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

Sometimes, a loop is nested in the loop. If you want to exit in the loop, you can use the tag:

outerloop:  for (var iI=0;iI<5;iI++) {      if (somethingIsTrue()) {          // Breaks the outer loop iteration          break outerloop;      }        innerloop:      for (var iA=0;iA<5;iA++) {          if (somethingElseIsTrue()) {              // Breaks the inner loop iteration              break innerloop;          }        }  }  
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.

And if you want to familiarize with Javascript irregularities, I suggest you visiting at wtfjs :).

This article is available at http://www.nowamagic.net/librarys/veda/detail/460.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.