Archive for the ‘technical level’ Category.

Do not use the innerHTML property on HTML objects

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\">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

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

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++) {
alertFunctions[i](); // 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++) {
alertFunctions[i](); // 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

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

  1. function function1() {
  2.         var var1 = 1;
  3.  
  4.         // Magic here! I create a function inside another function
  5.         function function2() {
  6.                 var var2 = 2;
  7.  
  8.                 // I have access to var1 defined in function1
  9.                 //(the parent function of the current one)
  10.                 alert(var1 + var2);
  11.         }
  12.  
  13.         // Call function2
  14.         function2();
  15. }
  16.  
  17. // Call function1 (should alert 3)
  18. function1();
  19.  

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.

  1. var globalTimer = null;
  2.  
  3. function createTimer() {
  4.         // I create the global timer
  5.         globalTimer = window.setTimeout(alertTimerId, 1000);
  6. }
  7.  
  8. function alertTimerId() {
  9.         // Alert the global timer ID
  10.         alert("The timer ID is " + globalTimer);
  11. }
  12.  
  13. createTimer();
  14.  

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.

  1. function createTimer() {
  2.         // I create an inner-function that alerts the timer ID
  3.         function alertTimerId() {
  4.                 // I call the "timer" variable from the parent function (using closures)
  5.                 alert("The timer ID is " + innerTimer);
  6.         }
  7.  
  8.         // I create the timer
  9.         var innerTimer = window.setTimeout(alertTimerId, 1000);
  10. }
  11.  
  12. 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

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
show_42() do | theNumber |
show_number(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.respond_to?(:walkLikeADuck).to_s)
puts “The cat can walk like a duck? ” + (theCat.respond_to?(:walkLikeADuck).to_s)
[/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)

How to make a singleton in javascript

[UPDATE : This post is outdated. Check out the new post on singletons.]

Singleton is one of the most common and easiest design pattern. In fact, a lot of designs are wrong just because the developer didn’t know about singletons and design patterns (I could have said : a lot of my designs were wrong just because I didn’t know about singletons and design patterns).

I was looking at the first three results for singleton javascript on Google and I was more than deceived by what they had to tell us. That’s why I write this article.

What is a singleton class?

A singleton is when your application needs to use just one instance of an object to centralize your access to it. Example, I have a list of cat names that can be used in various functions of an application. Sometimes, names are added or removed. I could use a global variable to the page containing the list. The problems are :

- It’s a global variable (global variables are bad).
- I don’t know when the list is created or initialized.
- If you reuse your class in another project, you will always need to define a global variable and instance it correctly.
- It’s ugly.

If I use a singleton pattern, the advantages are :

- The object is always correctly created.
- You don’t have to ask yourself questions about the state of the list or whatever. It just works!
- Another programmer can recognize the singleton pattern thus making it easier for him to work.

How to write a singleton class

Before writing a singleton, you need to know about creating objects and static functions.

  1. // I create the class
  2. function CatNames() {
  3.         this.names = new Array(); // The array that will contain the names
  4. }
  5.  
  6. CatNames.instance = null; // Will contain the one and only instance of the class
  7.  
  8. // This function ensures that I always use the same instance of the object
  9. CatNames.getInstance = function() {
  10.         if (CatNames.instance == null) {
  11.                 CatNames.instance = new CatNames();
  12.         }
  13.  
  14.         return CatNames.instance;
  15. }
  16.  
  17. // Function to add a cat name
  18. CatNames.prototype.add = function(catName) {
  19.         this.names.push(catName);
  20. }
  21.  
  22. // Function to remove the last cat name
  23. CatNames.prototype.removeLast = function() {
  24.         return this.names.pop();
  25. }
  26.  
  27. // Function to alert all cat names
  28. CatNames.prototype.alertAllCats = function() {
  29.         alert(this.names.join(","));
  30. }

I use it in these functions.

  1. function addThreeNames() {
  2.         // I use the one and only instance of the class (the magic of singletons)
  3.         var names = CatNames.getInstance();
  4.  
  5.         names.add("Mistigri");
  6.         names.add("Bibi");
  7.         names.add("Gary");
  8. }
  9.  
  10. function removeLastCat() {
  11.         // Once again, singleton is here
  12.         var names = CatNames.getInstance();
  13.  
  14.         names.removeLast();
  15. }
  16.  
  17. // I call the functions
  18. // – no need for a global variable
  19. // – no need to create the object and pass it as parameter
  20. addThreeNames();
  21. removeLastCat();
  22.  
  23. // Alert all cats
  24. var names = CatNames.getInstance();
  25. names.alertAllCats();

The downside of this technique

Yes I know, you can instantiate the singleton class if you want.

  1. var catNames = new CatNames();

You know what? You’ll have to follow a simple rule : never instantiate a singleton class. Maybe we could use more techniques that would protect you from instantiating your own singleton class but it would be a waste of time and code.

Do not use the style property on HTML objects

Since ajax, a lot of people have to create HTML on the fly depending on response of the request. One mistake that I see a lot is that people are using the style property of their HTML objects. Why shouldn’t I do it?

The style property has a precedence on every style

Because the style property is so “close” to the HTML object, it will override every other style from a CSS file. So if you begin to write styles in your javascript code, you’ll have to do it all the time. It might be easy and clean for a basic project but it will become a mess in the future. You should centralize every style in your CSS files so you won’t have to search where you assigned a style.

Example

I have this CSS

[source:css]
div.theCssClass {
background-color:blue;
}
[/source]

and I create a new HTML object of this class

[source:javascript]
// I create the DIV
var div = document.createElement(“div”);
div.appendChild(document.createTextNode(“This div is a test”));

div.className = “theCssClass”; // I assign theCssClass
div.style.backgroundColor = “red”; // The background is red

document.body.appendChild(div);
[/source]

You’ll see that the even if I set the background color to blue in the CSS file, the background will be red because I used the style property.

The !important in CSS

If you want to override a style assigned in javascript, you could always use the !important statement in your CSS file.

[source:css]
div.useThisOne {
background-color:blue !important;
}
[/source]

Use it only if you really have to. I wouldn’t recommend !important because it breaks the default behavior of styles and can become very messy. When all is important, nothing is important.

Looping through object properties and hash tables using the “in” statement

As I said earlier, objects are hash tables of properties and functions so looping throught them is done the same way (weepee!).

The “in” statement

The in statement must be used in a for loop. Like this : for (var element in allElements). In most of the other languages, the element variable would contain the complete element but in javascript, it contains the name that refers to the complete element.

Looping through a hash table

Before doing it, maybe you should take a look at How to use javascript hashes (or hash-table) to make sure you fully understand what are javascript hash tables.

[source:javascript]

// I create a hash table
var hashPetNames = new Object();

// I create the pets
hashPetNames["cat"] = “Mistigri”;
hashPetNames["dog"] = “Rex”;
hashPetNames["bird"] = “Bibi”;

// I loop using the “in” statement
for (var name in hashPetNames) {
alert(“My ” + name + “‘s name is ” + hashPetNames[name]);
}

[/source]

Run this code and you should see the alerts :
- My cat‘s name is Mistigri.
- My dog‘s name is Rex.
- My bird‘s name is Bibi.

So easy.

Looping through an object

This one is a little kinkier. Why would I want to loop through an object properties and methods? I can’t give you an answer. It’s up to you to find it. I’ve used it a couple of times so it’s not as useless as you could think.

Example, I would like to separatly alert all the properties and methods of an object.

[source:javascript]

// Create the class
function TheClass() {
this.name = “The class”;
this.fullName = “The full name of the class”;
this.age = “51″;
}

// Add a function
TheClass.prototype.alertClass = function() {
alert(this.name + ” ” + this.fullName + this.Age);
}

// Construct the object
var theObject = new TheClass();

// Loop through the properties/functions
var properties = “”;
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties += propertyName + “, “;
}
}

alert(“Properties : ” + properties);

// Loop through the properties/functions
var functions = “”;
for (var functionName in theObject) {
// Check if it’s a function
if (theObject[functionName] instanceof Function) {
functions += functionName + “, “;
}
}

alert(“Functions : ” + functions);

[/source]

How to use javascript hashes (or hash-table)

Javascript has no hash table object. In fact, all objects are hashes.

  1. var hashPetName = new Object();
  2. hashPetName["dog"] = "Rex";
  3. hashPetName["cat"] = "Mistigri";
  4.  
  5. console.log("My dog’s name is " + hashPetName["dog"]
  6.         + " and my cat’s name is " + hashPetName["cat"] );
  7.  

It’s a little overwhelming to write it like that so let’s use a simpler form.

  1. var hashPetName = {
  2.   dog: "Rex",
  3.   cat: "Mistigri"
  4. }
  5.  
  6. console.log("My dog’s name is " + hashPetName["dog"]
  7.         + " and my cat’s name is " + hashPetName["cat"] );
  8.  

Great! That’s it about javascript hashes, now I can go groom my cat.

Wait!!!

Why can I use an object to emulate a hash? Can I do the same thing with a Number object? Let’s try with the same code than above but with a Number instead of an Object.

[source:javascript]
var hashPetName = new Number(); // Magic is here!
hashPetName["dog"] = “Rex”;
hashPetName["cat"] = “Mistigri”;

alert(“My dog’s name is ” + hashPetName["dog"]
+ ” and my cat’s name is ” + hashPetName["cat"] );
[/source]

It works!!! What can we understand of this?

All objects are hashes too

When you are javascripting, forget everything you know about other languages, it won’t be any help.

I’m adding to the list

  • All objects are hashes

When we create an object, its properties and methods are added to the hash of the object.

[source:javascript]
// Create a class
function TheClass() {
// Adding a property
this.name = “the name”;
}

// Create the object
theObject = new TheClass();

// Alert the property name
alert(theObject.name);

// Alert the property name using the hash
alert(theObject["name"]);
[/source]

In this example, you see that using theObject.theProperty is the same thing that using theObject["theProperty"].

Dynamically add a property/method to the object

In my first example, I didn’t create the property in the constructor before using it. As you saw, it’s easy to dynamically add a property or a method.

[source:javascript]
// Create a class
function TheClass() {
}

var theObject = new TheClass();

theObject["age"] = 3; // Create a new ‘age’ property
theObject.fullName = “Mistigri”; // Create a new ‘fullName’ property

theObject.alertDetail = function() {
alert(this["fullName"] + ” is ” + this.age);
}

theObject["alertDetail"]();
[/source]

Beware! The new property/method will only be available to the instance you’re working on. If you want to add a new property/method to every instances of the class, use prototypes.

Using an array thinking it’s a hash

One of the most common mistake I see is to use an Array object thinking that’s the only one that you can use the brackets to create a hash. Even if it works, it’s not how it should be done. I recommend the use of Object instead.

[Update : A friend of mine pointed me out that I should have talked about hash tables (or associative arrays) instead of hashes.]

How to write constants in javascript

YOU CAN’T. As simple as that. Anyway, what is a constant? A constant is a unchangeable variable that throws an error when you try to write in it. Thus, implementing constant in javascript would be against its will to be opened. The magic of javascript resides in the liberty it gives you to change anything you want, anywhere you want. Even if you’re not the owner of the object. Even if it’s a javascript intrinsic class. Why would you want to have constants???

Still, everyone wants to use constants (myself included). Here are a couple of ways of doing it without actually doing “it”.

Global constants

Ouch! That one hurts! As I said earlier, global variables are prohibited since 1992 by GVIP (Global Variables International Police). But sometimes, a man gotta do what a man gotta do. If you really can’t find any better solution, use this one.

[source:javascript]
var DISPLAY_TYPE_SMALL = 0;
var DISPLAY_TYPE_BIG = 1;
[/source]

Class constant

If you already know how to create objects you have to use the class functions technique (also knows as static or shared functions) to create a class “constant”.

[source:javascript]
// Create the class
function TheClass() {
}

// Create the class constant
TheClass.THE_CONSTANT = 42;

// Create a function for TheClass to alert the constant
TheClass.prototype.alertConstant = function() {
// You can’t access it using this.THE_CONSTANT;
alert(TheClass.THE_CONSTANT);
}

// Alert the class constant from outside
alert(TheClass.THE_CONSTANT);

// Alert the class constant from inside
var theObject = new TheClass();
theObject.alertConstant();
[/source]

As you saw, you can’t access the constant using the this variable (a reference to the current object) because the constant is defined on the class only and not the object.

Class enum

Sometimes, constants are not enough. You need to regroup them to be more logical. Example? I have three different display type : small, medium, big. I could do this

[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE_BIG;
}

// Create constants
TheClass.DISPLAY_TYPE_SMALL = 0;
TheClass.DISPLAY_TYPE_MEDIUM = 1;
TheClass.DISPLAY_TYPE_BIG = 2;

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE_SMALL;
[/source]

It works but they are not logically grouped. I would prefer to use an enumeration (enum) [more info about enum].

[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE.big;
}

TheClass.DISPLAY_TYPE = {
small : 0,
medium : 1,
big : 2
}

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE.small;
[/source]

This is what I call beautiful code.

One simple rule

Knowing that there’s no mechanism that prevents you from modifying your “constants”, follow that simple law : don’t modify your constants.