Do not use the innerHTML property on HTML objects 2007-04-17

I already said Do not use the style property on HTML objects and as I was thinking how bad the innerHTML property can be, I considered doing an article on that subject. The problem was that stones were thrown at me after the first “Do not” article. Now I fear that this one may be worst… but I'll stand proud…

innerHTML seems easy

I like easy things : Diner Kraft and automatic cars. It's so easy to write HTML, why should I spend time with the DOM when I can easily do it with innerHTML?

With the Dom [source:javascript] var aLink = document.createElement(“a”); aLink.href=“http://www.javascriptkata.com”; aLink.appendChild(document.createTextNode(“Javascript Kata”); document.body.appendChild(aLink); [/source]

VS with innerHTML document.body.innerHTML += "<a href=\"http://www.javascriptkata.com\"&gt;Javascript Kata</a>"; Why???

innerHTML is dirty

It may look good at first sight but it'll look real bad the next morning without make-up. Did you noticed the \“? Prepare yourself because with innerHTML you will have a truck load of these. Take a look at this. document.body.innerHTML += "<a href=\"http://www.javascriptkata.com\" id=\"theLink\" class=\"aLink\" title=\"Javascript\">Javascript Kata</a>"; Ouch! My eyes burn.

A lot of HTML

iInnerHTML looks worst if you have a lot of And now, what if you have a lot of HTML code embedded in your javascript, it will win the war over you. I tell you.

innerHTML and ajax

I have an idea, if my ajax request returns some HTML, I could use the innerHTML property on an HTML object and assign the ajax response to it and it would be magic!

NO! In fact, you can do it but for every reasons in the world, don't ever do that. Yeah, I know, Yahoo!TV is doing it but don't fall in that trap.

Ajax should return data to your application. Why? Because you'll never know what you'll have to do with that information. For the moment, maybe you just do a simple display of the data but sooner or later, you'll have to re-use for another section of the page. If you return HTML, you will end up parsing it to extract the data contained in it. I tell you.

By the way, forget about that old XML thingy, try JSON

It is not standard

It doesn't really matter to me but if you're a W3C-compliant kind of guy, that may be a good point.

Your friend is a library

You have a lot a HTML code to produce through you javascript, go and get a good library. I can't tell you which one to use because they all have the ups and downs. Choose one and stick to it.


Javascript is not ajax 2007-04-13

I see a lot of person talking about how ajax is cool and it helps you doing things that you couldn't do before it was “invented”. What most of these people don't know is that most of the coolest features are not ajax. Ajax is just a way to communicate between a client and a server without reloading the whole page. The rest of it is javascript, DHtml (dynamic Html) and CSS (cascading style-sheet).

Ajax forces javascript

Most people hate javascript but they want to do ajax, this is a duality. How do they overcome that problem? By using tons of javascript library and copying javascript snippets from tons of different sites. You know what? That won't be any help for having well structured javascript. You just have to take javascript as seriously as your server-side language.

The structure

I saw a lot of web applications that were (almost) well documented. The developers spent hours thinking about doing a framework (argh!) that would help him handle all the code he will one day try to write. They didn't have any thought about how they would write the javascript that will handle all that shit. “It will just flow” they say. No. I won't “just flow”. It will be a mess.

Think about the javascript you'll have to write and treat it with respect.

DHtml???

Once again, people do not make any difference between ajax and DHtml. When something in a page moves, it's ajax. No, it's DHtml. Ajax is just the response from the server that triggered the moving request. With DHtml, you can dynamically change the Html of your page using Javascript/DHtml (hey, I'm not talking about the innerHTML property). That's where the javascript librairies (like jquery, script.aculo.us or mochikit) will help because the basic DHtml offered by javascript (with the DOM) is a real pain in the ass.

And CSS???

I also wrote Do not use the style property on HTML objects. That's where CSS enters the battle.


A common problem with the powerful javascript closures 2007-04-11

I recently wrote about closures and how easier your javascript will be to maintain and how good it will look. Now is the time for me to be a Closure-Grinch.

Closures keep a reference to a variable, not a copy

[source:javascript] // Create a Buy Viagra function function buyViagra() { var pills = 2;

// Create a closure to alert the number of pills
function alertPills() {
    alert("Number of pills : " + pills);
}

alertPills();

// Increment the number of pills
pills += 1;

alertPills();

}

buyViagra(); [/source]

Looking at this code, it can be pretty obvious that the alert containing the number of pills will be “2” the first time and “3” the second time. That's because the closures contains the reference to the variable and not a copy.

The common problem with closures and loop

That's a more common problem. We use closures in a loop (for or while) and it always keep the last value of the increment.

[source:javascript] // Functions that will alert a number var alertFunctions = new Array();

for (var iNumber = 0; iNumber < 3; iNumber++) { function alertFunction() { // We use the closures to have access to the variable “iNumber” (from the loop) alert(“Number is ” + iNumber); }

alertFunctions.push(alertFunction);

}

// We loop and call each functions for (var i = 0; i < alertFunctions.length; i++) { alertFunctionsi; // Call the function } [/source]

We would expect that three alerts pop having 0, 1, 2. But instead, it alert 3, 3, 3. This is because the iNumber variable was 3 when it got out of the loop.

How to solve the problem

[source:javascript] // Functions that will alert a number var alertFunctions = new Array();

for (var iNumber = 0; iNumber < 3; iNumber++) { // Magic here! var alertFunction = function(x) { return function() { alert(x); }; }(iNumber);

alertFunctions.push(alertFunction);

}

// We loop and call each functions for (var i = 0; i < alertFunctions.length; i++) { alertFunctionsi; // Call the function } [/source]

Step #1 var alertFunction = function(x) {

I create a new function that will take a parameter. The parameter will contain a copy of the variable I send to it.

Step #2 return function() { alert(x); };

I return a function that will alert the copied parameter of step #1.

Step #3 }(iNumber);

I call the newly created function (that returns a function).


The power of closures in javascript 2007-04-10

Now is the time. I can't go forward if I don't talk about closures. What are closures? Closures are your friend. That's the first thing you need to know about them. They will help you keep your code clean, healthy and easy.

A closures is created every time you create a function in a function (they are also created in other situations too but I won't talk about them now). When using a closure, you will have access to all the variables defined in the parent function (and all its parent functions too).

Attention! Before reading this article, you should take a look at 3 ways of creating functions in javascript.

Write your first closure

function function1() {
    var var1 = 1;

// Magic here! I create a function inside another function
function function2() {
    var var2 = 2;

    // I have access to var1 defined in function1
    //(the parent function of the current one)
    alert(var1 + var2);
}

// Call function2
function2();

}

// Call function1 (should alert 3) function1();

For the moment, it doesn't make sense but you will surely find a handy way of using it.

Example of a closure

Example of a closure, I want to alert the ID of the timer (returned by window.setTimeout) after 1 second.

In an old-fashioned (without closures) way, I would do the following.

var globalTimer = null;

function createTimer() {
    // I create the global timer
    globalTimer = window.setTimeout(alertTimerId, 1000);
}

function alertTimerId() {
    // Alert the global timer ID
    alert("The timer ID is " + globalTimer);
}

createTimer();

There are many problems with that code. The most obvious one is : it uses a global variable. You never know what happens to global variables between the time it is instantiated and the time it is used. It's bad.

In a new-fashioned (with closures) way, you would do this.

function createTimer() {
    // I create an inner-function that alerts the timer ID
    function alertTimerId() {
        // I call the "timer" variable from the parent function (using closures)
        alert("The timer ID is " + innerTimer);
    }

    // I create the timer
    var innerTimer = window.setTimeout(alertTimerId, 1000);
}

createTimer();

I have solved the global variable problem.

Now, what can I do?

Because closures are not implemented in every programming language (update : though it is not specific to javascript), you'll have to try it for yourself. I don't want to give you recipes on how/when to use it, it's up to you. But I could say that a great ajax web2.0 application normally uses a lot of closures.

Keep in mind that - Closures are created everytime you create a function in a function - Closures give you access to variables that are defined in the parent function (and all of its parents) - A closure keeps a reference to an object, not a copy (more on that later) - Watch out for memory leaks in Internet Explorer!!!


3 things that javascript and Ruby have in common 2007-04-05

When I decided to start Javascript Kata, a friend of mine just thought it was a cool idea and started his own site, Ruby Fleebie. I've never written code in Ruby but it looks like a very pleasant language. He borrowed me Agile Web Development with Rails: A Pragmatic Guide and I really liked the look of the code (by the way Frank, I'll give it back to you soon, promise). But as I am reading Ruby Fleebie, I always see similarities with javascript.

A great knowledge of javascript won't get you a job. But knowing a “serious” language + great knowledge of javascript and you will be rich (… but maybe not). So, why not take Ruby as the “serious” language as it is the rising star these days?

So here's a first draft of the list of similarities.

1. Everyone can modify your class structure

A lot of “serious” developers think about this as a weakness but this is the greatest thing that happened to languages since object-oriented. No more protecting you from yourself. Just that great feeling of liberty (you know the one when you are on the deck of a boat by a starry night with Leonardo DiCaprio behind you).

Ruby : 3 steps to understand how classes and objects work in ruby Javascript : What are javascript prototypes? (short answer for advanced javascripters)

2. You can pass a function as a parameter

In javascript, any function can be passed as a parameter.

[source:javascript] // Create a function that alerts a number function showNumber(theNumber) { alert(theNumber); }

// Create a function that “shows” 42 using // It takes as parameter the function that will show the number function show42(theShowNumberFunction) { theShowNumberFunction(42); }

// Call to show 42 show42(showNumber); [/source]

In ruby, it is called code blocks.

[source:ruby] // Create a function that alerts a number def show_number(theNumber) puts theNumber end

// Create a function that “shows” 42 using def show_42() yield(42) end

def main show42() do | theNumber | shownumber(theNumber) end end

[/source]

Ruby : An introduction to code blocks Javascript : 3 ways of creating functions in javascript

3. Walk like a duck?

You want an object to do something (walk like a duck) but you don't know the type of object and you don't know if it can.

In javascript, no problem, you just check if the object has the function (now that we know that objects are javascript objects are hash-tables)

[source:javascript] // Create a Dog class without functions function Dog() { }

// Create a Cat class with a walkLikeADuck function function Cat() { }

Cat.prototype.walkLikeADuck = function() { // Code to walk like a duck }

var theDog = new Dog(); var theCat = new Cat();

// Check if they can walk like a duck // by using [theObject].[thePropertyOrMethod] alert(“The dog can walk like a duck? ” + (theDog.walkLikeADuck != null)); alert(“The cat can walk like a duck? ” + (theCat.walkLikeADuck != null)); [/source]

In Ruby, it is simple too! Just use the respond_to method.

[source:ruby]

… code for creating classes …

Check if they can walk like a duck

puts “The dog can walk like a duck? ” + (theDog.respondto?(:walkLikeADuck).tos) puts “The cat can walk like a duck? ” + (theCat.respondto?(:walkLikeADuck).tos) [/source]

You'll see that only the cat can walk like a duck.

Ruby : What’s the fuzz about ducktyping? Javascript : How to use javascript hashes (or hash-table)