10 practical tips for JavaScript programming

  • 2020-03-30 02:40:52
  • OfStack

1. Variable conversion

It seems simple enough, but from what I've seen, it's common to use constructors like Array() or Number() for variable conversions. It is more efficient to always use raw data types (sometimes called literals) to convert variables without any additional impact.

var myVar   = "3.14159",
str     = ""+ myVar,//  to string
int     = ~~myVar,  //  to integer
float   = 1*myVar,  //  to float
bool    = !!myVar,  
array   = [myVar];  //  to array

The conversion Date(new Date(myVar)) and the regular expression (new RegExp(myVar)) must use constructors, and the regular expression must be created in the form of /pattern/flags.

2. Convert from decimal to hexadecimal or octal, or vice versa

Would you write a separate function to convert hexadecimal (or octal)? Stop it now! There are easier off-the-shelf 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. Play with Numbers

In addition to what you saw in the previous section, here are some more techniques for handling 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

5. Use window.name for simple session processing

This is something I really like. You can specify a string as the value of the window.name attribute until you close the label or window. Although I do not provide any scripts, I strongly recommend that you take full advantage of this approach. For example, it is useful to switch between debug and test modes when building a website or application.

6. Determine if an attribute exists

There are two aspects to this problem, both when checking the property and when getting the type of the property. But we always ignore these little things:

// BAD: This will cause an error in code when foo is undefined
if (foo) {
// 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") {
// BETTER: This doesn't cause any errors and in addition
// values NULL or false won't validate as true
if (window.foo) {

However, in some cases, when we have deeper structures and need more appropriate inspections, 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) {

7. Pass arguments to functions

When a function has both required and optional arguments, we might do this:
function doSomething(arg0, arg1, arg2, arg3, arg4) {
doSomething('', 'foo', 5, [], false);

Passing an object is always more convenient than passing a bunch of arguments:
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;
  arg1    : "foo",
  arg2    : 5,
  arg4    : false

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

8. Use the document. CreateDocumentFragment ()

You may need to append multiple elements to the document dynamically. However, inserting them directly into the document results in the document having to be rearranged one at a time. Instead, you should use the document fragment and append it only once:

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

9. Pass a function for the replace() method

Sometimes you want to replace part of a String with some other value. The best way to do this is to pass a separate function to string.replace (). Here's a simple example:

var sFlop   = "Flop: [Ah] [Ks] [7c]";
var aValues = {"A":"Ace","K":"King",7:"Seven"};
var aSuits  = {"h":"Hearts","s":"Spades",
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. Use of labels in loops

Sometimes, the loop is nested inside the loop, you may want to exit the loop, you can use the label:

for (var iI=0;iI<5;iI++) {
  if (somethingIsTrue()) {
  // Breaks the outer loop iteration
  break outerloop;
  for (var iA=0;iA<5;iA++) {
    if (somethingElseIsTrue()) {
    // Breaks the inner loop iteration
    break innerloop;

Related articles: