5 Good and Small JavaScript Tips and Tricks

If you are a professional programmer or senior coder to one or many programming languages, certainly we will always have some little tips and tricks to solve the some problems better, and the web JavaScript programming language also is not an exception. This JavaScript tutorial is the results from the author's experience with 5 JavaScript tips and tricks that they are very small, compact but extremely useful for working with JavaScript.


Sampled by © JavaScriptBank.com

It is advised, when deploying a live website, to group all your Javascript files into a single one, and reduce its size by removal of all unnecessary clutter. You obviously get a few nasty surprises the first time you do this, such as dead code (or debug-only code) being included or two incompatible files being included together. The usual answer to this, like with any integration-related issue, is to perform continuous integration, and generally make sure during development that the final product works as it should.

Tip #1 - Keep it all together

I generally keep all of my javascript together in one single file, which is accessed through http://domain/all.js or something like that. Of course, that file is in fact generated from a well-tended garden of neatly arranged source files, but the intent is that every single visit on the development website will bring along all the code that could possibly conflict with it, to identify issues as soon as possible.

This means I have access to a Javascript preprocessor, because generating a single file already involves reading all the files.

Tip #2 - Conditional inclusion

Difficult bugs appear on platforms with  no debuggers, which means you need to be able to track the progress of your application with logging. You don't want to have those log lines appearing on the live website, though. In the same way, runtime assertions are useful while developing, so you get a clean "Expected string, got array" error message right after you call a function with incorrect parameters, instead of a "object has no member charAt" ten stack layers deeper. Yet, assertions use up room, and tend to die in a flashy and unprofessional way on a live website.

An overly intrusive preprocessor can prevent your code from running if not preprocessed. It also means whatever tool you use to edit Javascript source cannot recognize the syntax anymore, which is bad. The solution (which I learned from the PHP preprocessing techniques of the folks at IntellAgence) is to embed preprocessing information in comments.

Need some logging?

/*<*/ log('Hello'); /*>*/

Need to check something at runtime?

/*[*/ Assert.areEqual(x,y); /*]*/

A simple regular expression can remove these from the final code, but you can also selectively disable them by removing the second slash of the first comment :

/*[*  Assert.areEqual(x,y); /*]*/

Tip #3 - Named anonymous functions

Quick reminder: Javascript allows you to define anonymous functions using a lambda-like construct:

function(x) { return x + 1 }

This acts like a function literal (pretty much like a string literal works for strings, or an array literal works for arrays). In fact, if you're doing any kind of serious Javascript, you probably have anonymous functions all over the place, such as callbacks to asynchronous operations:

$('button').click(function(){ alert('Hello') });

Or you might be defining member functions for your classes:

className.prototype.setFoo = function(x){
  this._foo = x;
};

When you get a runtime error, the debugger displays a stack trace containing the names of the functions and the places where they were called. So, if you were using many anonymous functions, you get neck-deep into layers of "anonymous" on your stack trace. Sure, you can click on every single one of them to understand what is happening, but it is way faster to get that knowledge from looking at meaningful names.

Javascript allows you to give names to anonymous functions. In fact, this is how recursive functions can be defined as lambdas (a feature that OCaml lacks, for instance). So you can write the following and see it appear in a stack trace:

$('button').click(function _onButtonClick(){ alert('Hello') });

className.prototype.setFoo = function _className_setFoo(x){
  this._foo = x;
};

I start all names with underscores, because a simple /function _[A-Za-z0-9_]*/ in my preprocessor can identify and remove all those names when I don't need them.

Tip #4 - Are your callbacks called?

The Javascript function model lets you write a function that forwards whatever it was doing to another function. You can even log some information along the way...

function trace(f) {
  return function () {
    log('%o.%s(%o)',this,name(f),arguments);
    return f.apply(this,arguments);
  }
}

The preprocessor instructions for conditional removal let you do this only in specific circumstances:

className.prototype.setFoo = /*[*/ trace /*]*/
(function _className_setFoo(x){
  this._foo = x;
});

It can also be quite practical to use a variant of the trace function that stores all functions it traces in an array, and removes them from the array the first time they are called. This can be useful when debugging calls to asynchronous functions that you write, because you might forget to call the callback function when you are done, and these bugs are otherwise quite hard to identify.

Tip #5 - Do not rely on closures too much

Closures in Javascript means you can write this, and have the inner function use the variable from the outer function :

function outer(a) {
  var b = a + 1;
  return function inner(c) {
    return b * c;
  }
}

Closures are extremely useful. However, Javascript has a nasty habit of creating variables at global scope whenever you try to write to a variable that doesn't exist. For instance, the following function is not re-entrant because an accidental typo makes it use a global variable :

function person() {
  var aeg = 18;
  return {
    setAge : function(a) { age = a },
    canDrink : function() { return age > 20 }
  }
}

A good solution, I believe, is to rely on object members instead of variables. Inappropriately using an object member is harder than inappropriately using a local variable, because the former does not default to "look in the global scope". Besides, every function beyond a certain level of inner state complexity deserves to be adapted to a more structured object style with its data as private members (if only because this is way easier to explore with a debugger).

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com