How to make sure undefined is not defined

Think about it, you write a plugin or a library (let’s name it jsKata) and your code contains checks to see if certain things are undefined.

Here’s an example :

  1. if (obj.name === undefined) {
  2.   obj.name = "This object has no name";
  3. }

This code works well until you include another script (found on an obscure website) and it breaks your previous code. By debugging the code, you see the value of undefined is no more undefined but false.

Yes, I know that you thought it was impossible to define undefined but it is, you just have to write undefined = false.

Redefine undefined

There’s two way of redefining undefined and they both use self-invoking functions.

Method 1 : Scope your code

  1. (function(undefined) {
  2.   /* your complete code here */
  3. })();

As you see, the self-invoking function has one parameter named undefined. At line 3, the self-invoking functions is called without any parameter. It results that the parameter has the value undefined (or it is defined to undefined if you prefer).

Take a look at this javascript :

It will display false and then display undefined even if undefined was globally defined at first.

This is the HTML that goes with it :

You can also execute it here.

Method 2 : Globally redefine undefined

There’s another method but I don’t like it that much. It redefines undefined but nothing protects it from being badly redefined in another chunk of code.

undefined is a global variable accessible using the global window object. Line 2 defines undefined and line 3 display the value of undefined as false. On line 4, I use a self-invoking function as method 1 does but now, I define the global undefined variable through the global window object.

The HTML of this example :

You can also execute it on jsFiddle.

Other methods

Some commentors pointed me other ways of doing it.

You can use typeof :

  1. typeof undefined == "undefined"

Or you could use void(0), it always returns undefined

  1. undefined === void(0) // this returns true

Creating namespaces with self-invoking functions

When a project’s javascript grows, it can be easy to lose ourselves, buried under thousands of lines of js code. That’s why I like to create namespaces to keep everything together.

Let’s say I have functions to work with cats and I create a namespace for it because there are lots of other functions related to dogs.

As you see, to access the cat list I must use the complete name including the namespaces like this : Animal.Cat.list. You can guess that it will get pretty long as the code grows.

Let’s make this call shorter.

Now, I only have to write c.list because c is an alias of the Animal.Cat namespace. Thanks to self-invocation!

You probably noticed that the code is longer but this is just an example. In a real situation, this technique would make your code much clearer.

Don’t forget to subscribe to my newsletter!

Self-invoking functions explained line by line

I never knew it was possible to love a syntax but since, I fell in love with the self-invoking function which can be summarized like this : (function(){})(). Yes this is a valid syntax though it doesn’t do much in this form (it creates a function that does nothing and call it).

Some people call it self-invocation or self-executing but I don’t think it has an official name.

Let’s break it down

It will become clearer if I execute some code and write it on more than one line :

  1. (
  2.   function() {
  3.     console.log("this line is called");
  4.   }
  5. )
  6. ();

Line 1 : (
This first parenthesis is used as grouping operator. Read more here and here.

Line 2 : function() {
This create an anonymous function. I could write something like function doSomething() { but in the case of a self-invoking function, this is useless because the function is in its own little scope (line 1) and can’t be called from outside of it.

Line 3 : console.log(“this line is called”);
This is the code that will be invoked.

Line 4 : }
This clauses the function opened at line 2.

Line 5 : )
Clauses the parens opened at line 1.

Line 6 : ();
We call the function created at line 2 and returned within the scope from line 1 to 4.

Let’s write it in a more compact syntax :

  1. (function() {
  2.   console.log("this line is called");
  3. })()

See my post about using self-invoking functions to create namespaces.

Don’t forget to subscribe to my newsletter!

Ready.js – continuous integration using jslint, nodejs and git

Ready.js is a tool to prepare your javascript files for production. It can be used in every type of web project (Rails, Django, node, etc). It does four things :

  • Check if your javascript are valid with jslint.
  • Minify your javascript with Closure Compiler (optimize and minify your code).
  • Watch your javascript files for jslint while you’re coding.
  • Create an aggregated file of all your javascripts.

Ready.js is written in node.js and the source code is available on github.

How to install it

First, all you need it to install git and node.js. Then, you do the following :

  1. run git submodule add git://github.com/dsimard/ready.js.git ready.js
  2. run cd ready.js && git submodule init && git submodule update && cd ..
  3. Create config file in your_project/ready.conf.js :

     { src : "./javascripts", // the source dir of js files
       dest : "./minified", // the destination of your minified files
       minifiedExtension : "min", // Extension of the minified file
       runGCompiler : true, // if should run GoogleCompiler
       aggregateTo : "./minified/all.js" // Which file to aggregate all javascript files
     }
    
  4. run echo 'node ready.js/ready.js ready.conf.js' >> .git/hooks/pre-commit

Then, every time you commit, ready.js will be run. You can see alternative installations on the github page.

Why this tool?

First, I wanted to write something in node.js. Javascript is a long time favorite of mine and I’m really excited about node. Second, I wanted to have a build tool for jsKata and I hated all of them. Third, I don’t like the “cache” principle in Rails and wanted to have something else.

Try Ready.js today!

Alternatives to singletons in javascript

Singletons are quite popular on this blog. A lot of people are coming here from that search. In a sense, I’m happy to have such a considerable traffic from google. On the other hand, I’m not proud that this post is my most popular. Why? Because I don’t believe in singletons in javascript. This concept belongs to more object-oriented languages, even though we can have an half-baked OO in javascript. Singletons are just too much of a hassle compared to a simpler solution.

What is a singleton?

A singleton is a design pattern. When instanciating a singleton class, it will always return the same instance of the class. You can’t create more than one instance of the class no matter how many time you call the “new” operator.

Some people think that singleton shouldn’t be a pattern. Personally, I never use it in javascript because they are not “javascript-friendly” (in fact, the whole concept of OO is not javascript-friendly). Here’s what I do.

The alternatives

Just between you and me, when we want to use a singleton, it’s probably because we want to encapsulate a certain part of the code to be easier to read and understand.

Alternative #1 : simple and clean

The easiest way of encapsulating functionalities is to create an object. Sure, it’s “untyped” but types don’t mean a lot in a dynamic languge like javascript. You have to learn to work with it. Here’s how I do it (view on github).

Alternative #2 : more complex

Let’s say you have a big project and you want to really separate every functionalities in “namespaces”, it would be easier to use a more complex technique.

You can take a look at jsKata where every library I wrote has its own namespace (jsKata.undo or jsKata.timezone). jQuery is also using this technique (source code).

Let’s say you have a 2 levels deep namespace but you use the alternative #1 as described ealier. You would end up with this (view on github).

As you can see at line #6, the reference to your msg variable is pretty long. If you have a lot of code, it would become redundant.

If you want to keep your code readable, it’s a good idea to use a self-invoking function like this (see on github).

Let’s study it line by line.

var instance = (function() {
//… code is here…
})();

This is the self-invoking part of the technique. You see that function(){} is in parenthesis. So the result of the parenthesis is a function object (and not the result of the function). After these parenthesis, there’s an empty set of parenthesis. It means that the object function in parenthesis is called.

var i = {
// … more code …
}

This creates a scope. At this moment, the i variable is used as a shorthand for myApplication.instance.

hello : function() {
alert(i.msg);
}

As you can see, we can use i in the hello function to get the msg variable.

return i;

Finally, by returning i as the result of the function call, it gets assigned to myApplication.instance.

No more singletons please

When you know these techniques, I can’t see any reason of using singletons anymore. Forget about using javascript as if it was a complete object-oriented language and start using it as it is.

Auto-detect timezones, time zone offsets and daylight saving in javascript

I had to work with timezone on the project I’m working on and I hate it. So I created jsKata.timezone to deal with them (view documentation).

How does it work?

In short, this library doesn’t do a lot but saves you a lot of troubles. It returns the standard time offset of the user’s browser. From there, you can narrow the list of possible time zones for a user. To have the standard timezone offset simple call :

  1. var standardOffset = jsKata.timezone.st();
  2. /* or you can also call a shorter version */
  3. standardOffset = jsk.tz.st();

You can see a demo.

Other functions

  1. // Return the daylight saving time offset
  2. var daylightSavingOffset = jsKata.timezone.dst();
  3.  
  4. // If the time zone has daylight saving
  5. jsk.tz.hasDst();
  6.  
  7. // Return the standard time zone as a string (ex : -0500)
  8. jsk.tz.stToString();
  9.  
  10. // Return the daylight saving time zone as a string (ex : -0400)
  11. jsk.tz.dstToString();

Under the hood

You can’t have a named time zone in javascript (example : eastern time or central time), you can only have a time zone offset which is represented by universal time (UTC) minus the distance in minutes to it by calling dateVariable.getTimezoneOffset(). It means that if the time zone offset is -1 hours of UTC, javascript will give you 60. Why is it inverted in javascript? I have no idea.

In winter, it’s always standard time. In summer, it’s daylight saving time which is standard time minus 60 minutes… but not for every country. Plus, summer and winter are inverted in the southern hemisphere. That’s a lot of exceptions and that’s why I created the jsKata.timezone library.

NoFreeze : a library that avoids freezing in javascript

The unresponsive warning happens a couple of time a year but every time, it’s frustrating. It prompts the message “A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete“.

I launched jskata not a long time ago and mostly talked about the undo feature. Now, I will talk about the jskata NoFreeze library to avoid freezing by splitting long processes into smaller ones.

You can look at the demo, the documentation or the source.

Old plain loop

This script loops the index variable from 0 to 1000000 and writes the current value in document.title. Unfortunately, it will freeze the page until the whole process is done.

  1. var index = 0; // index
  2. for(index = 0; index <= 1000000; index++) {
  3.     document.title = index;
  4. }

How to write a responsive for

I’m using jsKata.nofreeze library to avoid the freeze. This script will do the same as above. But, the page will remain responsive during the whole process.

  1. var index = 0; // index
  2. jsKata.nofreeze.forloop(
  3.     // the condition
  4.     function() { return index <= 1000000;  },
  5.     // the incrementor
  6.     function() { index++; },
  7.     // this is what will be executed
  8.     function fct() {
  9.         document.title = index;
  10.     }
  11. );

It uses closures to keep a resemblance to a good ol’ for loop.

Other loops : infinite and each

There are two other loops available. Infinite will loop indefinitely until you stop it. Each will loop through the properties of an object and loop in each one.

Take a look at the documentation to know more about them.

How to stop a process

As you see, every functions (forloop, infinite and each) return an object containing a stop function. So to stop a single process, just call it.

  1. var loop = jsKata.nofreeze.infinite(function() {//do nothing});
  2. loop.stop();

If you want to stop all the processes of a page, make this call :

  1. jsKata.nofreeze.stop();

More to come…

There’s much more you can do with that library but I wanted to keep it simple for this post. Next, I’ll talk about multi-process and other kinds of loop.

Announcing the jsKata libraries

I’m officially announcing the jsKata librairies.

Why?

I just wanted to write some public code and share it with others. Javascript has a lot of pains in the butt and jQuery is not the answer to every problem. jsKata is the answer to some of the problems that I face everyday while writing javascript.

A manifesto?

I wrote a manifesto because it helps me focusing on what and how I want to achieve with jsKata. This is the manifesto of version 0.2.

  • No internal dependence : every library can be used independently “as is”.
  • No external dependence : don’t depend on external libraries.
  • Everything is public : you know what you’re doing
  • Avoid objects : use closures
  • No unnecessary validation : if something goes wrong, an error will pop
  • No error catching : if an error pop, it goes all the way up
  • No DOM : jQuery already exists
  • No plugins : if a developer wants to add something, he will find a way around
  • Write good documentation : document as I code
  • Promote : a good library is nothing without users

What are the libraries available?

I don’t consider jsKata to be a library but more a set of libraries because each one can be used independently (see #1 in manifesto). For the moment, there are two librairies.

Undo & redo
I wrote about undo and undo & redo before. I took the code and put it in jsKata. You can look at the code or try the demo.

No freeze
This librairy is to avoid unresponsive script warning when you have a really long loop. It cuts a loop to create digestible chunks without a warning. I’ll write more about this one in the future but meanwhile, you can look at the code or try the demo.

GitHub

All the code is hosted on GitHub. I hope you will enjoy it!

How to de-anonymize your anonymous functions

First of all, de-anonymized functions are called named functions and they look a lot like “regular” functions (in fact, they are).

Why should I de-anonymize?

For debugging. Instead of having a stack trace filled with ?() (representing an anonymous function), it is nicely printed and easier to follow.

For self-reference. Example, when you want an anonymous function to recall itself recursively, you would have to call arguments.callee. It’s odd and it’s deprecated anyway (people pointed to me that it’s not really deprecated but it throws an error in ECMAScript 5 strict).

Stack trace of anonymous functions…

If you run this in your firebug console (every javascripter should have firebug).

You get a stack trace that looks like this :
func()
func()
func()

… versus stack trace of named functions

You get a stack trace that looks like this :
f1()
f2()
f3()

As you can see, it’s a lot easier to debug and to understand who’s calling who.

Warning : There’s a bug in IE with named functions.

Recursive anonymous function

Let’s create a recursive anonymous function that counts to 10.

And let’s create it but using a named function.

Once again, the code is much clearer and it’s not using a deprecated element.

A note about closures to advanced javascripters

I just wanted to say that in the last example, you could have written this :

As you can see at line 4, I call the count function which is not the name of the function but the variable to which the function is assigned. It works, but it may not be the best thing to do. You can learn more about closure on that previous post and I’ll write more about it.

An undo/redo library for your app

I wrote about undo before and I pushed it farther. What about an undo/redo system? I extended the v.01 of the undo and I now handle undo and redo in the same object.

Annoucing redo in jskata.undo

I made a new version of jskata.undo still hosted on GitHub. If you look closer, it is now part of a library called jskata that is not officially announced. My next post will talk about it in details.

Demo

Take a look at the demo. The javascript of the demo is available here. You can see the complete doc on GitHub.

How does it work?

Execute an action that you can undo/redo

Doing something requires calling execute with 2 functions as parameters : the do and the undo.

Undo and redo the last action

Very easy!

Events and properties

For the moment, jskata.undo has just one event : onChange.

There are 2 properties : canUndo() and canRedo().