5 conseils JavaScript Bon et les petites et astuces Si vous êtes un programmeur professionnel ou codeur supérieurs à un ou plusieurs langages de programmation, certainement nous aurons toujours des petits trucs et astuces pour résoudre les problèmes un peu mieux, et le langage de programmation web JavaScript n'est pas non plus une exception. JavaScript tutorial est le résultat de l'expérience de l'auteur avec 5 JavaScript conseils et astuces qu'ils sont très petits, compacts mais très utile pour travailler avec JavaScript.

Étiquette: 5, Trucs et astuces, programmeur professionnel, codeur principal, langage de programmation, problème, expérience

Gratuit iPage hébergement Web pour la première année MOMENT

Si vous êtes toujours à la recherche d'un fournisseur d'hébergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Crédits supplémentaires gratuites pour le paiement de 24 mois ($45)?

Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'êtes pas aussi! Plus important encore, lorsque vous enregistrez l'hébergement web à iPage grâce à notre lien, nous allons être heureux de renvoyer un plein remboursement. C'est génial! Vous devriez essayer iPage hébergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
Essayez iPage GRATUIT première année MOMENT

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 () {
    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).

JavaScript par jour

Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web