Ajax and javascript don’t use threads 2007-06-04

Since ajax, a lot of people are thinking that asynchrone means “in a separated thread”. They are wrong!

Synchronous

The XMLHttpRequest object gives you the option to make a synchronous request to a server with the parameter async set to false. It means that when you call the server, all javascript executions will stop and wait for the server to respond to the request. I never saw it used. In fact it is more confusing that anything else because the page seems frozen and users don't like frozen things. If you use it, you are not cool!

Asynchronous

Now you are being cool! The asynchronous is used by everyone and it doesn't freeze the page while the call to the server is done. So, if you have a call that takes 30 seconds before receiving the answer, your users will never know that you're a bad server-side coder that do not optimize the code he's writing (I'm just joking).

The misconception of asynchronous

People take for granted that because it's asynchronous, it's a thread. They are partially right. There must be a thread created by the browser to keep the javascript running while it makes a request to the server. It's internal and you don't have access to that thread. But, the callback function called when the server responds to the ajax request is not in a thread.

I'll explain clearer. If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called). That's because javascript itself doesn't create a thread to execute the ajax response from the server and simply waits that all executions are terminated before starting a new one.

So if you're running a lot of ajax requests simultaneously, you might get some weird behavior because they will all wait one on another before executing themselves.

UPDATE 2007-06-12

Following one of my readers comment (BK), I have written a sequel to this article : Ajax, javascript and threads : the final truth.


Ask Dan a javascript question : first edition 2007-06-01

I proudly announce a new attracting feature for javascriptkata.com : Ask Dan a javascript question. What is Ask Dan a javascript question? Ask Dan a javascript question is the new attracting feature of javascriptkata.com. Readers (you) ask Dan (me) a javascript question and that will be answered on javascriptkata.com. There's more! When asking Dan a javascript question, you could receive an answer and a link to your site… for free! Isn't it exciting? And you know what? Ask two questions and receive… not zero… not one… but two answers and links to your site. Isn't it awesome?

I began by asking some friends to ask Dan (me) a javascript question. Here they are… and you know what? You can read them for free!

PM asked Dan : Does javascript can become a sort of bisexual slave that makes my toasts every morning? Answer : I'm afraid that the answer is no. Javascript doesn't offer that kind of feature but maybe you could be interested in How to use JSON.

Emile asked Dan : If a kid wants to begin using javascript, does he need a 10 000$ computer or he can use a metal wire and a battery to create binary? Answer : You know what? It's up to you to decide which one suits you best. 10 000$ computer? Fine. Metal wire and battery? Fine too. Isn't it a perfect world? By the way, maybe you could be interested in How to use JSON.

Now, it's up to you to Ask Dan a javascript question by sending a mail to dan@javascriptkata.com.

Did I mention that sending an email is… free!


3 reasons why I use jQuery 2007-05-29

These days, you can't write a web application without using one of the billionth javascript library. Two of them stood out of the crowd : prototype and jQuery. I will explain why did I choose jQuery.

Prototype

Prototype is comfortably installed in a lot of developers mind because of two reasons : it was the first widely used and script.aculo.us. Being the first accepted library is a hard thing to do and it will always help them. Scriptaculous (I hate to write it with the dots) had an incredible effect on the popularity of prototype. For the first time, we could do “flash animation” without using flash. This was instant popularity.

jQuery

jQuery is one of the bastard child of prototype. It reuses the $() function but brings it to a level you never could have hope for. In fact, jQuery is almost completly based on the $ sign. Why? Maybe because it's fast, maybe because it's trendy. I don't know. Example, you want to download a JSON from a server, $.getJSON(“http://www.thesite.com/thejson”).

Reason #1 : The selectors

jQuery supports a lot of selectors. And when I say a lot, I really mean a lot. First, there's CSS selectors. You just have to apply what you know about CSS and you can write many complex selectors.

Second, there's XPath selectors. When I was young (sic!), I wrote a lot of XSL. And when I say a lot, I really mean a lot. XSL makes an intensive use of that XPath thingy. Because XHTML is basically XML, we could use XPath to easily navigate throught the DOM. The problem was that before jQuery, nothing could do that. Now, we can!

In comparison, prototype just has the $('theId') to select a element. Ouch!

Reason #2 : The Attributes

It's easy to add/remove attributes to any HTML element. I use it when I create new elements or when I need to add/remove a css class on an element. The interesting thing is that you can chain them and it will work. Example, I want
$("div").attr("title", "This is a div").addClass("newClass");
You can add as many as you want…

Reason #3 : Ajax and JSON

Once again, ajax is now easy as 1,2,3. I wrote an article on JSON and in my mind, there's no real alternative to JSON. jQuery helps you with it.
$.getJSON("http://www.thesite.com/thejson",
    function(json){
        alert("I received the json and put it in the json var : " + json.toString());
    }
);
It's a little more complex with prototype.


How to know if it's a leap year 2007-05-24

It always happens : you have some calculation to do with a date and you forget to calculate those friggin' leap years. Here's how to do it cleanly.

The first way

Almost every one use this simple rule : if it's divisible by 4, it's a leap year. So the code is
var isLeap = theYear % 4 == 0
Wait a minute, I forgot something! If it's not divisible by 100 but by 400 it is not a leap year… or maybe divisble by 100 and not by 400…

I can't remember that! Let's do it another way.

The one and only way

var isLeap = new Date(theYear,1,29).getDate() == 29;
Nice! That's something simple that I enjoy. Let's dissect it.
new Date(theYear, 1, 29)
This line simply create a date object that is initialized with the variable theYear. 1 is the month. As in java, the months are 0 = january and 11 = december (I hate that!). 29 is the last day of february when it's a leap year.
.getDate()
Returns the date part of a date (sic!). It means that for May 23, 2007, it will return 23.
== 29
That's the magic part of it. As I said in Mastering the date object in Javascript, there's a special twist that let you work with dates differently than in most of the languages that I used before. When you initialize a date at the 29th day of february on a non-leap year, it will simply use the date March 1, 2007. So a call to the getDate() function would return 1 and not 29.


How to inherit classes in javascript 2007-05-22

First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

Note! Before reading this article, you should take a look at How to create objects in object-oriented javascript.

A one-liner

To inherit a class in javascript, it's a one-liner
TheSubClass.prototype = new TheParentClass();
As simple as that!

Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.
/* The constructor of the Mammal class */
function Mammal() {
}

/* The constructor of the Cat class / function Cat() { } // The magic that inherits Cat from Mammal is here!!!!! Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!
/ Above code goes here */

// Create a cat var theCat = new Cat();

// Check if the cat is an instance of the Cat class if (theCat instanceof Cat) { alert("theCat is an instance of the Cat class"); }

// Check if the cat is an instance of the Mammal class if (theCat instanceof Mammal) { alert("theCat is an instance of the Mammal class"); }

If you execute this code, you'll see that the cat is an instance of the Cat class and the Mammal class.