Archive for the ‘white belt’ Category.

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…

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.

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.

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.

3 ways of creating functions in javascript

In javascript, all functions are an instance of the class Function (with a capitalized F).

The old way

Everybody knows how to do it. In fact most languages do it this way. Boring but you can’t write javascript without knowing it.

[source:javascript]
function f() {
}
[/source]

The uppercase F way

You can directly create an instance of the Function class this way.

[source:javascript]
var f = new Function(“alert(‘Function called’);”);
f();
[/source]

The problem with that is that the code of the class is passed as a parameter of the constructor. A lot of people use this method to create “dynamic” functions but they do just because they don’t know of the lowercase f way of doing it.

[source:javascript]
var i = 100;
// “dynamically” alert the i variable
var alertNumber =new Function(“alert(‘Number is ” + i + “‘);”);

alertNumber();
[/source]

It looks bad for such a simple example. It gets uglier as it gets more complex. Please, don’t use this method.

The lowercase f way

This one is the one you’re looking for. Why? Because it is as handy as the uppercase F but you don’t have to write the code as a string. Example, I dynamically load an image and I want to alert when the image is ready.

[source:javascript]
var img = new HtmlImage();
img.src=”…”;

var onLoadFunction = function() {
alert(“Image is ready!”);
}

img.onload = onLoadFunction;
[/source]

But wait!

As I was writing this, I realized something that I didn’t realize before. The old way of writing functions is not as boring as I thought.

[source:javascript]
function parent() {
function child() {
alert(“Child function called”);
}

// Assign the function to a variable
var childFunction = child;

childFunction();
}

parent();
[/source]

Executing above code will alert “Child function called”. So, javascript also creates a variable called child when I write function child() {}. Interesting.

What are javascript prototypes? (longer answer)

[I've also written the short answer (for advanced javascripters)]

Javascript is using prototypes and is the only language I know that is doing it. What is the idea behind it? Simple. With prototypes, you can extend (add methods/properties) any class you want anywhere you want anytime you want even if you are not the owner of that object. Object-oriented purist will be shocked but I am more than pleased with that.

Why using prototypes?

It’s memory-friendly
By adding a method to a class prototype, you are creating a single occurence of the function that is referenced by every objects of that type.

It’s easy

To add a method to a class, no need to create a new class. Juste write TheClass.prototype.theMethod = function() {//code here} and it’s done.

It’s fun!
Maybe not as fun as drinking kool-aid but compared to the complexivity of other languages, we have a champ.

How to use prototypes

Simple. Write the [NameOfTheClass].prototype.[NameOfTheExtension].

You want to add a trim function to the String object? (thanks Greg for the correction)

[source:javascript]
String.prototype.trim = function()
{
return this.replace(/^\s*|\s*$/g, “”);
}
[/source]

You want to add an oldValue property to the string

String.prototype.oldValue = “the old value”;

Beware! All the new String objects and the one already declared will have a property with the value “the old value” inside. I can’t think of a particular reason why one would do this. If you have one, please comment.

How to create objects in object-oriented javascript

[UPDATE : This post is outdated. Check out the new post on how to create objects.]

Javascript is a functional programming language thus having no “real” objects. You can write it the way you want : procedural spag, functional, object or whatever word you know. Why should I write it object-oriented? Because, OO has proven many times its ease of use and great encapsulation. In this paper, I won’t talk about why but about how.

There are hundreds of way of writing OO javascript, I tried a lot of the most commons and I finally adopted one : oo using prototypes.

1. Creating an empty class

I like cats so here’s a complete example for a cat that meows.

First, I create an empty class.

[source:javascript]
function Cat() {
}
[/source]

Hmmmm… that looks a lot like a function. In fact, it’s a function. Why classes are function? Because javascript is a functional language. More on that later (maybe).

2. Creating the constructor

When I have a cat that meows, I want to see its name. I add a name property that is initialized in the constructor of the class.

[source:javascript]
function Cat(name) {
this.name = name;
}
[/source]

What is this? This, is a reference on the current instance of the object. By calling this.name = name, we instantiate an public variable for the object that has the value name (the name of the cat).

3. Adding a instance method

As I said earlier, I want the cat to meow. So, I will add a meow() method to the class that will be available to every instance.

[source:javascript]
function Cat(name) {
this.name = name;
}

Cat.prototype.meow = function() {
alert(“meow!”);
}
[/source]

I used the class’ prototype. This is one of the hundred ways of adding a method but it’s the best way because we create a single reference for all the objects of that class.

4. Using variables of an object

Hey, didn’t you read the specs? I said that I wanted to see the name of the meowing cat.

[source:javascript]
Cat.prototype.meow = function() {
alert(this.name + ” : meow!”);
}
[/source]

Did you see? I used the this (reference on the current instance of the object). By doing that, I simply call the variable that I defined in my constructor (see point #2).

5. Making the cat meow

Now I’m ready to make the cat meow. On the onload property of the body element, I call a function named bodyOnload.

<html>
<body onload=’bodyOnLoad();’ />
</html>

In the bodyOnLoad function, I create a Cat object and call the meow() method.

[source:javascript]
function bodyOnLoad() {
var mistigri = new Cat(‘Mistigri’);
mistigri.meow();
}
[/source]

I should see an message box with the message “Mistigri : meow!” inside.

In conclusion

Ok, that was an easy one but though it may seem obvious to you, it is not alway as clear for some of my fellows. The important thing I wanted to show was how to create a class method (see point #3). This is the best/safest/fastest way of doing this.

5 reasons to write object-oriented (oo) javascript

To write hard as a rock javascript, the first thing you need to do is to object-orient your code. I do not mean to have a class structure that could stand the passage of a sandstorm in the Sahara but a light and useful structure that will let you work elegantly.

This article does not explain the techniques behind the reasons. It is written for the sake to make you change the way you develop in javascript.

Go read this article if you want to see some code.

1. Packages/namespaces : no more 152 characters prefixes to ensure uniqueness

Packages/namespaces (packages = java, namespaces = .NET) are not the greatest thing since slice bread (did you forget about kool-aid?) but they are the handiest solution to avoid methods, objects or constants to have the same name. I give you a simple example.

I have two methods :

  • one that truncates a string of its last character (who wants to do that???)
  • one that truncates a number of its decimals

I would write these methods :

  • truncate(theString)
  • truncate(theNumber)

The problem is that they have both the same signature. How can javascript differenciate the two and call the good one? It can’t.

With packages/namespaces, I could have the following signatures to differenciate them.

  • com.CompanyName.String.truncate(theString);
  • com.CompanyName.Number.truncate(theString);

Of course, I could have done it a million ways (extending String and Number objects, give them different names, etc) but for the purpose of the demonstration, I have done it that way.

2. Work locally : forget about global variables circa 1987

Global variables are prohibited since 1992 by GVIP (Global Variables International Police). Every variable of that type is seeked and destroyed by them. With javascript, the difference is that a global variable is not “global to the entire application” but global to a page. That’s the gray zone. There’s no strict law against that and people think that it’s OK to do so. They are wrong! A web application that heavily relies on javascript would have dozens of dozens of global variables and would soon become a 3500 pieces puzzle.

Object-oriented javascript allows you to work locally on each variable by making it static (shared for .NETters) or using closures (subject of another article soon!) within an object.

3. Ajax : be a part of web2.0

You want to be the next golden-boy of the web2.0 era? Better start using Ajax now. But wait! Ajax is a mess with all of those callback, failure and timeout functions here and there. Will it stop me from being a billionaire?

No. Object-oriented javascript permits you to stay clean by encapsulating all those ugly functions in objects. Hey, here you’ll need closures too! The last step you need to do is to stay away from drugs. Drugs are bad for your health and they could kill you before you reach your goal. Did I mention “Don’t run with scissors”?

4. Inheritance : for greater powers

I wouldn’t recommend you to use inheritance just to impress women. Inheritance is far too complex for its benefits (you won’t get more women) unless you have a very complex application. And by complex, I mean more complex than building a space shuttle.

Now you are warned. Inheritance is the “most common” principle behind object-oriented and can be implemented in javascript. No, you won’t have the handy extend/inherits or whatever statement in oo language. Maybe this will keep you from over-designing your code so it’s not that bad after all.

5. The future : javascript is already there

Javascript is a step ahead of a lot of programming languages. Sure, it is copied on such and such obscure language but it is the most widely known language that first used closures, functionnal programming, untyped variables and so on.

Java programmers, in their glass tower, think of javascript as a disordered mutant of their beloved language. They are wrong! Javascript only shares its syntax. The most recent versions of Java are now implementing closures and varargs. Looks like the natural selection from Evolution theory has done it again.

If you want to see code for doing object-oriented javascript, read this article.