Mastering the date object in javascript

Javascript has a pretty basic Date object. It is cool but not as cool as in other languages. In fact, it is different but we like it anyway.

The primitive value

A date is nothing else than the number of millisecond since January 1, 1970 00:00:00. So now is 1 177 603 737 358.

When you create a Date object, it is initialized at now. To alert the primitive value (the number of milliseconds since 1970), I simply do.

  1. var now = new Date();
  2. alert(now.valueOf());

Adding and subtracting

Note : You have to know that months in javascript are 0 = january and 11 = december. Just like Java.

This one is easy. When I want to add a number of days (or anything else) to a date, I use the getDate() and setDate() function. When you don’t know that the setDate() function (and setHours, setMinutes, setMonths…) has some magic in it, you may have a hard time manipulating the dates.

So, I want to add 3 days to the current date.

  1. var now = new Date();// Add 3 days
  2. now.setDate(now.getDate() + 3);
  3. alert(now);

The problem is when you want to add 3 days to December 31 2006, it should return January 3 2007. No problemo!

  1. var now = new Date();
  2.  
  3. // Set to December 31 2006
  4. now.setYear(2006);
  5. now.setMonth(11);
  6. now.setDate(31);
  7.  
  8. // Add 3 days
  9. now.setDate(now.getDate() + 3);
  10.  
  11. alert(now);

You see that the date is correctly computed. You can do the same things with all the other parts of the date. Magic is in the air!

No formatting

There’s no way of formatting a date to a string except if you use concatenation.

If you want to display the YYYY-MM-DD format, you’ll have to do this ugly code.

  1. var now = new Date();var nowStr = now.getFullYear().toString() + "-" +
  2.     (now.getMonth()+1 < 10 ? "0" + (now.getMonth()+1).toString() : (now.getMonth()+1).toString()) + "-" +
  3.     (now.getDate() < 10 ? "0" + now.getDate().toString() : now.getDate().toString());
  4.  
  5. alert(nowStr);

Maybe you won’t do it as ugly as this but it won’t look pretty. Maybe you should check for a librairy.

The Date.parse() function

Don’t use the Date.parse() function. I don’t even know which format it takes. It looks like month[sep]day[sep]year but I’m not sure. Better use some regexp and use the set[DateUnit]() function accordingly.

getYear() VS getFullYear()

You should not use the getYear() function. For an obscure reason, it returns the number of years since 1900. You don’t want to use it. Trust me.

You are now a master

That’s what you need to know about javascript Date object, you are now mastering it.

Do you have something else to add?

Do not use javascript for validations

This one will be widely accepted. The problem with it is that it’s so obvious that the question is asked here and there.

Javascript is not secure

I repeat : javascript is not secure. Your code is readable and it can be modified by anyone. It is great when you want to do a bookmarklet. It is not so great when you want to have a hard as a rock web application.

Example, you want to validate that a manually entered date is less than today. The javascript code for it is not complex.

[source:javascript]
function validateDate(theDate) {
var now = new Date();
return (theDate < now);
}
[/source]

But anyone could override the function to always return true and all the dates that he enters would be good. This is bad.

Always validate on the server-side

Whenever you have to validate something in your web application, use the server-side. I know, it is redundant and long to do but you must do it. Someone once said that you must consider every input from the user has evil.I prefer the word dirty. Users sometimes don’t want to be evil to a web application but they are. And sometimes, users want to be evil.

If you have little time to implement an application, just do the server-side validations.

You must consider javascript validations as “pretty” validations. It validates things but it just to make your application prettier. In facts, it helps you with usability and it simplifies the life of the users of your application.

The “cheap return” method

To avoid to write a lot of code on the server-side for validations, I would suggest you a simple method that will help you code faster. It is called the cheap return method.

  1. You do all the validations on the client-side in javascript.
  2. You do all the validations on the server-side but if it fails, you display a generic page to the users that says that it has failed.
  3. You pretend to have done it completly on the client-side and server-side.
  4. You spend the rest of your time watching the ceiling.

The idea behind that is that if all javascript validations have passed, the users must have done something between the client-side and server-side. So, he is responsible of that error.

I don’t really like it either…

The problem with bookmarklet

I talked earlier about bookmarklets and how wonderful they are. In today’s web2.0 world, you can’t have a successful application without giving your users a cool bookmarklet. It can be easy to do sometimes (like the one of del.icio.us) but you always want to do more and it gets more complex… until the day you hit the wall

The problem

You can’t execute code without a click of the user. It is obvious to 99,42% of you, but there will be a day when you’ll just say “I want to execute some friggin’ code without a click from the user”. Even if you want to do it to simplify the life of the user, you can’t. There must be a solution.

The solution

For now, the solution is called GreaseMonkey. This is a Firefox add-on that executes javascript automatically when certain pages are called.

Example, I want every background color of every web page I visit to be gray. I would create a script with this code


document.body.style.backgroundColor = "gray";

and it would just work.

The problems of the solution

It is Firefox only. With around 75% market shares, Internet Explorer just can’t be forgotten.

It is too complex
. The user has to know how to install add-ons and how to install greasemonkey scripts. It is way to hard for a normal user.

The real solution

I don’t have one and that’s why guys that I ask you : how to execute javascript code automatically without a click from the user?

I want all the solutions you can give to me wether it is real or fantasy.

Thanks alot!

How to do a bookmarklet with javascript

The day I discovered it, I was really happy. Not happy as a fish in water but maybe happy as a cat having its meal (though it enormously depends of which cat we are talking about). Talking about bookmarklet to some of my friends, I saw that there were a lot of incomprehension about it. So I’ll begin at the beginning.

What is a bookmarklet?

A bookmarklet is a chunk of javascript code that can be added as a bookmark in your browser. When you click the bookmark, the javascript is executed. This can do a lot of things.

To add a bookmarklet, simply drag the link into your bookmark toolbar.

Why does it work?

It works because when a page is loaded in the browser (the client), it has complete power over it. Using javascript, you can do whatever you want without being stopped by some kind of security. Isn’t it wonderful?

How to do a bookmarklet

1. Write some javascript that does something useful
2. Put it in a link with the command javascript: before it and void(0); (just to be safe) after it
3. Tell the people to drag the link in their bookmark toolbar

I have to say that the javascript code has to be less than 2083 characters, the limit of characters that enters in the address bar in Internet Explorer.

How to import another JS in a bookmarklet

You want to have a complex “application” executed on a page but you can’t do it in less than 2083 characters? As I said earlier, the client has the complete power over the currently displayed page so you can import javascript files in the current page.


var script = document.createElement("script");
script.src="http://www.example.com/javascript.js";
document.body.appendChild(script);

Now, put that on one line add javascript: at the beginning and void(0); at the end and you’re set.

Now, let your creativity flow and make a great application.

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.