Monday, December 16, 2013

What is this undefined thing??

There is a lot of confusion around undefined in Javascript. It seems that many of the developers do checks for undefined without fully understanding what exactly is going on. I think that confusion comes from the fact that undefined is one of the primitive datatypes Javascript comes with, but it's also a property on host object (window in browser environment). So if you imagine:


which you probably are familiar with, the location is property on window object. This will return location object when accessed. undefined is also a property on window object and its perfectly legal to call:


or in modern browsers:


When accessed this window.undefined property will return undefined primitive.

It will not return an Object, it will not return a string or a number or boolean which are Javascript datatypes that you are probably familiar with. This property will return primitive undefined that along with string, boolean etc. is simply one of the datatypes that Javascript comes with.

So few examples. What happens when I do check as below?

if(someVar===undefined) {}

someVar is compared against window.undefined property. As this is simply a property on window object it might contain anything really, not necessarily undefined. Imagine someone evil putting this somewhere in a code:


Bad things will happen, people will get fired and projects will be late and anyone without understanding of undefined will be screwed. Now, I might get jumped in here by some developers who actually prefer above syntax over typeof someVar==="undefined". As this is uncommon to reassign undefined property, IMO its fine to use either as long as you understand what is happening (this includes understanding why === is used rather than ==). 

Good news is that in modern browsers with ECMAScript 5 this property is read only, however it's still possible to screw thiongs up for everyone involved with:

(function() { 
    var undefined=66;
    alert(undefined); // will output 66

Ok, another example. Truly silly code ever popular nevertheless:

if(someVar==='undefined') {}

So what is happening here? Some poor dummy compares someVar to "undefined" string basically. He might as well do someVar==='Homer likes beer' and get similar result.

So how to check if something is undefined? Most people seem to prefer:

if(typeof someVar==='undefined') {}

Or if you must:

if(someVar===undefined) {}

Given that you understand what is happening.

To sum it up:

1. undefined is a property on host object (window in browser environment)
2. undefined is primitive datatype Javascript comes with. null, string, boolean etc. are other datatypes you probably are familiar with.
3. although unlikely, undefined property can be assigned different value but only truly evil programmers do that. Be aware however, they are among us.

Friday, December 13, 2013

Making sense of Javascript task queues processing

It seems that even seasoned JavaScript developers having trouble understanding how task queues are organised in JavaScript and what the order of tasks execution is. It seems pretty  straightforward till you run into situation where it just doesn't make sense. In this post I will try to clarify important details of how task queues are organised. Lets start from beginning  and build on examples as we go.

JavaScript is a single threaded language. It basically means that only single block of the code can be run at a time. Program simply runs line by line, through loops, conditionals etc to its end. Sometimes its quick and sometimes it takes long. If so then browser indicates its busy. This in turn often results in "Unresponsive script" sort of popup as below:

Consider this code:


<div id="box">nothing here yet</div>


var box=document.getElementById("box");

for(var i=0;i<10000000;i++) {

It starts a fairly long loop and inside of the loop div is updated with current value of i. As you will see when the program runs, browser will not respond and will look busy. The div that is being referenced inside of a loop will most likely not show updated value till the loop ends and program exits.

Now, two very important points:

1. If the browser will update the UI and when this is gonna happen depends on browser implementation. Most likely it will happen when the program will run to the end but its totally up to the browser.

2. Browser will not respond to asynchronous events e.g. mouse clicks as long as the single thread of JS code runs. Click all you will, nothing will happen till the very end. Program will not jump to any handler and will keep running till its finished. No magic here, one thread only.

To confirm just that try the code below. This time we added mouse click listener that opens alert when document is clicked.


<div id="box">nothing here yet</div>


var box=document.getElementById("box");

document.onclick=function (e) {

for(var i=0;i<10000000;i++) {

Now, while program runs click somewhere in in the document. None of the browsers respond when the script is busy. So what happens to asynchronous events when single JS thread runs? Are these completely lost? Not to worry.. these are put in a task queue so their callbacks could be executed when currently running JS program reaches its end.

Now imagine that instead of click event some other event occurs e.g. window load event, timeout is fired etc. Each of these would be placed in a task queue.

Ok, this is straightforward stuff so lets take it a bit further and have a look at code below:


<div id="box">nothing here yet</div>


function homerSays() {
    alert("hmm.. Doghnuts...");

setTimeout(homerSays, 5000);

document.onclick = function () {

for (i = 0; i < 1000000; i++) {

Again it seems straightforward, the result however, depending on a platform you use, will surprise many. It simply schedules function call in around 5 seconds (setTimeout(..)), then attaches listener to click on document and runs fairly long loop.

Now it would seem that when you click the document before 5 seconds has passed it should schedule click event and place it in a task queue. Then after 5 seconds is passed timeout event should fire and should be placed in a queue again, somewhere after earlier click event. One might think its certain that when the program is finished the outcome will be alert with "DOH!" (from click callback) followed by alert with "hmm.. Doghnuts..." (timeout). Once again however this depends on browser implementation. Run the code above in various browsers and see for yourself. E.g. I consistently get different results in Chrome and Firefox.

To see why this is happening lets go line by line and explain details.

When program runs it gets to the line with:

setTimeout(homerSays, 5000);

So what happens now? At this point its extremely important to understand few points:

1. The line schedules event to be fired in 5 seconds from this very point. This is important not to get confused and understand that this will be fired (as close as possible to) 5 seconds from now, NOT from when the execution of JS will finish. Pretty basic stuff yet many gets confused.

2. At this point there is nothing placed into task queue just yet. Event will be placed into a task queue at the time when its fired, so in around 5 seconds from now. Program might be still running by then and event will have to wait in a queue for its execution.

3. Program registers onclick handler and enters a loop.

4. The loop is running now and setTimeout has not fired yet as 5 seconds has not passed. User clicks mouse button. As program is busy and this places click event in a task queue.

5. 5 seconds has passed and timeout fires. This places timeout event in a task queue as well.

6. Loop finishes and alerts pop up on the screen.

Now, lets take Chrome as an example. Surprisingly timeout handler will be executed first, even though that mouse had been clicked before timeout fired.

Why is this happening then? It's happening because browser might maintains more than one task queue. Its important to know that how many task queues for event types are maintained it depends on browser implementation. According to specs it might be one single queue for all event types, or multiple queues, each for specific event type. 

Specification is pretty clear on it:

For example, a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else.

So depending on platform events will be placed all in one or in more specific queues. So what is the big deal you ask? No matter how many queues, these events should be processed in order, right? If click happened before timeout fired it still should be executed before the timeout task? The answer is it depends on browser implementation. Once again specification clarifies that:

The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order.

The example above clearly gives different results in different browsers. To sum it up if there are events in different task queues its totally up to a browser to decide which queue should be processed first. Without knowing this its nearly impossible to understand browser behavior at times.

Ok, to sum all the above up in few short points:

1. Only on thread of JavaScript can run at a time. If JavaScript runs and asynchronous even occurs (click, timeout fires etc.) this event is put in a queue.

2. Browser might have one or more task queues. User interaction events e.g. mouse clicks, keypress etc. might go in one queue, timeouts in other and so on. This depends on browser implementation.

3. When JavaScript program runs to its end browser decides which task queue needs to be processed first. This again depends on browser implementation and its easy to get confused when things seem out of order.

Monday, December 9, 2013

How to prevent container element with floats from collapsing?

Everybody knows that having number of floated elements inside of a container will cause outside container to collapse. If you look at the code below its not surprising that someContainer div will fold as three boxes inside of it are floated:


<div class="someContainer">
    <div class="someFloat">Float 1</div>
    <div class="someFloat">Float 2</div>
    <div class="someFloat">Float 3</div>


    border: 1px solid green;   

    width: 100px;
    height: 100px;
    border: 1px solid #f00;
    float: left;

Now, the most common solution to prevent someContainer from collapsing is to use some sort of clearfix at the end of someContainer div. Its usually class involving clear: both. Its sort of dirty solution as it pollutes HTML with unnecessary markup. There is pure CSS solution to this problem and its as simple as adding overflow: auto to someContainer class. Modified CSS is below, I also created fiddle in here:


    border: 1px solid green;   
          overflow: auto;

    width: 100px;
    height: 100px;
    border: 1px solid #f00;
    float: left;

In my opinion this solution is way cleaner and faster then ever popular clearfix. It does the trick in most cases and even old and already forgotten browsers.


Saturday, December 7, 2013

More than just a function

When you start working with Javascript there is a good chance you will start using functions as building blocks of your program. Many programmers however do not realize that pretty much ordinary code as below creates two objects:

function Human() {
   // some code

function Dog() {
   // some code

Yes, you can call it as a function by Human() or Dog(), but you need to be aware that this is actually an object, with its properties, parent object and methods.

The objects above are Function objects. In addition to objects we just created there is already whole bunch of objects available in JS. Many of these e.g. Array, you are probably using everyday without much thinking. Function object is one of them.

As "inherit" is not really correct term for describing how JS organizes its objects into hierarchy, lets just say that Human and Dog functions objects above have internal property (link so to say) that reference a Function objects prototype property.

In ECMAScript documentation this internal property is referred to as [[Prototype]]. This property is not available in all browsers and it should not be used for anything more than debugging. In some implementations e.g. in Chrome if you should be able to access it via __proto__:


Every object in JS has this internal link. Function objects (such as Dog and Human we created and others e.g. Array) point to Function.prototype. Other objects will point to their respective prototypes e.g. when you create var cards=[] it will create Array object with cards.__proto__ referencing Array.prototype.

Its also worth noting that in modern browsers (and IE9+) you can access [[Prototype]] via Object.getPrototypeOf(instanceName) function. 

So you can imagine Function object as sitting above Human and Dog objects higher in hierarchy. So our hierarchy can be described as:


This Function.prototype property in turn via its [[Prototype]] property also has link to prototype higher in hierarchy. It is linked to Object.prototype property that sits on top of hierarchy. So to further describe relationship:


Now if we continue this trip and we as for Object.prototype.__proto__ we will get null as Object sits on top of hierarchy.

Ok, so we know what happens when we declare a function. We actually create Function object. We also learned that all objects have internal [[Prototype]] property. Unlike other objects however, function objects have two very important qualities:

1. can be used as constructors
2. its instances contain prototype property

These are important and very interesting topics and I will possibly cover these in future posts. I covered only tip of the iceberg here I hope that someone also found this useful however.

Wednesday, December 4, 2013

Why not to use new Array()?

Yeh, why not? Simple. Take an example below and please be patient, I'm going somewhere with this:

function orderBeers()
// drinking beer, around 10 beers usually does it
return 10; 

The code above creates a function, but more importantly it creates orderBeers property on global object which in browser environment happens to be a window.

Now, global object has heaps of properties e.g. locationprint and among many others Array. We use this all the time without much thinking. So our orderBeers property references the function we just created.

Ok, so now some malicious, no beer drinking programmer might not agree with our beer drinking policy and might override our function so it returns 0:

function orderBeers()
// no beer for anyone
return 0;

And there goes our fun. Now, think about this. We can do it with our orderBeers function and so we can do it with Array, right? Take this code:

function Array() {
// some code

var myArray=new Array();

Instead of JS Array we will get Array object we defined. This will not happen when we use [] syntax:

var myArray=[];

Ok, who would o such a thing you ask? Well, although this is unlikely in my opinion however its important to understand why this is possible. 

Monday, December 2, 2013

Selecting layers in Photoshop with one click? Really??

Fireworks (RIP) made it pretty easy to select layers and on mouse over. It was even highlighting what will be selected on click. Genius! Photoshop however is not that easy. Too many times I've seen users who claim they know Photoshop but struggle with something simple as selecting layer under the mouse cursor.

Example.. Imagine working with Marquee Tool. You made your selection there is however wrong layer selected. Sure you can go to layers palette and dig out layer you need. Wouldn't that be easier just to click the layer you after though? Well in Photoshop it is possible after all and the magical shortcut is:


Right, there you have it. This is for Windows of course. I'm guessing on Mac you would have similar combination. I hope someone will find it useful.

Native app to record and score Brazilian Jiu-Jitsu fights

I always have lots of ideas in my head, for various applications, interfaces and all this geeky stuff. I also enjoy Brazilian Jiu-Jitsu and as there are heaps of really, really low quality apps for BJJ I decided to put these 2 together and create something that might be of use for some.

I looked on Google Play and couldn't find anything that would be remotely useful so I came up with this idea of an app that could record the video of the fight, keep track of all points and what not. After a while I had it ready and now for all you BJJ fanatics its all good and published on Google Play.

It basically allows you to record the video of the fight and during recording you can assign or deduct points to each fighter. It stores the video that can be later replayed at any point. Its built in custom video player replays the video and displays scores as the time goes.

App has has various options, screen layouts and many others yet I believe I made it simple enough to be actually useful and not clutter app with unnecessary stuff.

Its important to mention that this is not some pathetic HTML5/Phonegap combination pretending to be native app. Phonegap wouldn't be able to pull it off. All this is written in Java and as this is native app it works pretty fast. It supports Android 2.2 and newer, no iPhone version sorry.

Sunday, December 1, 2013

Is event handler attached to element?

Not so long ago I had a task to develop a website and as I wouldn't deliver anything less then awesome (such a curse of mine ;) I decided to load every page via ajax. This in combination with HTML5 history API allowed me to provide out-of-this-world-experience for end users so no visible page reloads and what not.

Needles to say I had to deal with event handlers. Attaching these as necessary and making sure same event handler is not attached twice to the same element. So to check what was on .quickPreview I went with standard:


.. and to my surprise it didn't work as expected. Instead of Object I got undefined. Not cool so I started googling and it wasn't long till I discovered that above was removed from jQuery 1.8:

$(element).data(“events”): In version 1.6, jQuery separated its internal data from the user’s data to prevent name collisions. However, some people were using the internal undocumented “events” data structure so we made it possible to still retrieve that via .data(). This is now removed in 1.8, but you can still get to the events data for debugging purposes via$._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

So the workaround is to use:

$._data($(".getAquoteButton")[0], 'events');

Its definitely good enough for debugging however as per documentation this might change from version to version so I would rather not use it for production code.

(Not so) easy posting as guest via Disqus API

I was asked to use Disqus as a comment system for one of the Wordpress powered websites I've been working on. Piece of cake I thought and sure Wordpress comes with plugin that I can install, customize and the job is done. Well, this is true for plugin installation part, not so much for styling and modifications though. Wordpress Disqus plugin doesn't allow any real customization. You can set it's appearance to "For light backgrounds" or "For dark backgrounds" and change typeface to serif/sans-serif but not much more than that. Furthermore, Disqus loads everything in iframe and there goes your customization via usual css/javascript tricks. To make things worse  I was provided with design that was nothing but ordinary. 

Right.. they must provide some API I thought and so with a bit of PHP coding, with help of curl here and there I should be able to pull it off. And so I started digging through docs provided.

For a start I tried to pull out the comments and got what I wanted. The trouble started however when I tried to post a comment as a guest. Disqus requires public key to be used when posting a comment, neither of the keys provided when I registered application was working though. The code below kept giving me message "This application cannot create posts on the chosen forum" or "Invalid API key".

$session = curl_init('');
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1); // instead of just returning true on success, return the result on success

$args = array(
'message' => 'DOH!',
'thread' => '1234567890',
'author_name' => "Homer Simpson",
'author_email' => "",
'api_key' => 'someApiPublicKeyGoesHereButWhereToFindItGodOnlyKNows'


$data = curl_exec($session);

I was getting annoyed at this point and decided to have a peek how plugin itself does it. Sure it must pass some api_key to backend and in fact it does. I looked up the ajax call and there it is:

I plugged it into the code above: 

'api_key' => 'E8Uh5l5fHZ6gD8U3KycjAIAk46f68Zw7C6eW8WSjZvCLXebZ7p0r1yrYDrLilk2F'

and voila, it worked. 

This cant be right I thought. Unless I'm missing something this key is nowhere to be found in application settings page. I couldn't dig it up from documentation either. Where to find it without peeking up ajax calls? What will happen if Disqus will decide to change the api_key at some point? There goes my comment system, right? It's sure looks like it. So I decided to do more research and it appears that someone else had similar problem. Just have a look at this StackOverflow thread:

There is screenshot attached showing api_key and guess what..? It looks exactly the same as the one POSTed from my installation. 

So now I can post as a guest, but is it a solution? Well, like everything else it depends on your project. The way I understand it now the whole thing is really disappointing. Unless you are happy with default look and functionality Disqus provides, prepare for some struggle.