Monday, August 12, 2013

I'm still alive - !false and !undefined in JavaScript

Hi all, I've been very busy lately, and then I went for a holiday, so I didn't update the blog. Sorry!
I recently came back from the seaside and started to work on a bug I had since forever. I thought it was a deeply rooted bug that was spread in different methods. It turns out it was not like that. And that's what I discovered:

First of all, I had this array that kept count of how many distributed processes answered a pull request. Each process has an ID, and it corresponded with the index of the array. The array first is filled with false values. As an example, imagine process ID 0 that is polled. At first the value in the array at index 0 is false, but when the process answers, I set the value in the array at index 0 to true.

If the process don't reply after a certain threshold time, I execute something. I used to check this by going through the array in this way:

for(var i = 0; i < processes.length; i++)
        //do something

In other words, if array[i] is false, it means the process did not answer.
This could look correct if only I would take into account the fact that, concurrently, some processes may be spawned, thus increasing the processes array. Since I didn't polled the newborn processes, I don't want them to be checked. Of course, with the shown code, this was happening. Luckily, JavaScript fills with undefined the indexes of an array which have not be initialised; but on the other hand the evaluation of !undefined is the same as the evaluation of !false. This clearly lead to a bug which always executed something, even if it was not the case. Again, luckily with JavaScript I could correct this very easily:

for(var i = 0; i < processes.length; i++)
    if(array[i] === false)
        //do something

And that's it!


  1. When viewing rolex replica watches, you should take into consideration the band, as well as the face of the watch. The band or strap can make a striking difference in the watch's appearance. Normally hublot replica are either made out of leather or metal. Some people find leather more comfortable, but it wears out after tag heuer replica uk and must be replaced. Leather bands are generally preferred by people who like a low key appearance. Some individuals rolex replica sale opt for leather because metal is harsh on their skin. Metal straps, which usually need to be fitted by adding or subtracting links, can be crafted out of replica watches sale silver or titanium. What kind of strap you choose will depend on your tastes, or that of the person you are shopping for. Designer watches can look amazing with any kind of strap, however the look will be replica watches sale different based on the type you select.

  2. Thank you very much for for your great information. It really makes me happy and I am satisfied with the arrangement of your post.
    duck life 5
    vex 3