Thursday, December 27, 2012

A JavaScript Quiz and a JavaScript Quiz Engine

Here is a very simple JavaScript quiz for you to try and have some fun with!
For this quiz, I wrote a very simple quiz engine using JavaScript and some JQuery APIs. To create a quiz all you need to do is create a JSON object which contains Question / Answer info and pass it to a single API. The engine will:
  • determine if a question has a single answer or multiple answer and show radio buttons or check boxes accordingly.
  • display user progress
  • display results and correct / incorrect questions.
Source code is on my GitHub. I have also put the files on github pages. So if you want a quiz on your site, import the engine by simply importing the CSS and the JavaScript (ensure you also have JQuery being pulled in from somewhere).


Then create a JSON object of your questions and answers. The JSON object is an array of Question / Answer. Each element in the array consist is a map of three elements:
  • The question
  • The possible answers (the answers to present to the user) - specified as an ordered array.
  • The correct answer
For example:
var quiz_questions = {questions:[
                             {"question":"Which of the following is a risk of using Constructor function?", 
        "answers":["If it is invoked without using new keyword, the this variable is not bound to local object but to the global namespace.", "Performance risk", "There are no risks"],
        "correct_answer":"0"}, 
        ...]
The correct answer is a numeric value, which represents the position in the list of the possible answers. If there is more than one correct answer, separate the correct answers by commas. For example:
{"question":"Which of the following is true about functions?",
        "answers":["Functions can be expressed as literals", 
                   "Functions can be assigned to variables, array entries and properties of other objects",
             "Passed as arguments to other functions",
             "Returned as values from functions",
             "Can have properties created and assigned dynamically",
                                           "Can solve climate change?"],
         "correct_answer":"0,1,2,3,4"}
The engine will use check boxes for questions that have multiple answers and radio boxes for questions that have a single answer. To invoke the engine, it is just one API.
quizModule(quiz_questions, $('#intro'));
In this case $('#intro') is the dom element I want the quiz to sit below. quiz_questions is the JSON object containing the question / answer pairings.

There is no server request handling whatsoever after the quiz loads. Everything happens client side from the first question to the generation of results.

If you have any interesting JavaScript questions send them on and I'll add them to the quiz! Or use the engine and create your own quiz.

Wednesday, November 21, 2012

The Technology Radar

Acclaimed IT Consultancy company ThoughtWorks recently published its October Technology Radar.
This publication assessess software techniques, software tools, software platforms, software languages and makes recommendations regarding the various offerings.

In a world where the technologies changes are rapid and where choices can seem overwhelming it is a super publication and well worth reading. It is not everyday when industry Gurus such as Martin Fowler (Chief Scientist at thoughtworks) are going to tell you their expert opinions for free.  Some of the interesting points from the latest technology radar:
  1. The proliferation of work - in - progress limits. One method to achieve this is to use Kanban limits. "Kanban" traces back to the early days of the Toyota Production system and in English it is roughtly translated to "signboard". One aspect of the Kanban system is to limit impedemence mistmatch between inter-dependent processes by imposing work-in-process limits. So there is not point having a massive amount of development in progress at any one time and then all a sudden dumping this on a test teaam.
  2. 'Mobile first' - this is a technique which considers the mobile devices rather than last.  Some simple stats substantiate this:
  3. Regarding the build tools, Maven is going out of fashion. Interestingly because it never fully dumped XML.  I tend to agree with this.  While Maven offered some improvements over Ant in how it handled Maven, if you wanted to do anything which was not the Maven way you had to write a plugin which some people found hacky especially as project complexity grows.  Rake and Gradle offer better alternatives.
  4. The testing framework Jasmine for JavaScript gets a lot of praise.  QUnit (the one from JQuery which this blog covered recently) doesn't get any. Jasmine is more geared towards BDD whereas QUnit is more TDD.
  5. Very interestingly the performance and scalability tool Locust is suggested over JMeter. One advantage Locust has is that it is not thread bound. This means you do not need a separate thread to simulate every client.  to simulate some geographical dispersion amongst your clients  Saas Performance testing tools such as Blitz.io and Tealeaf are suggested as tools on the up.
  6. The most popular project in GitHub (over 40,000 stargazers at time of writing), Twitter Bootstrap is promoted for its powerfuls of components and features. I really like the look of Twitter Bootstrap. It is used by NASA, MSNBC and practically every start up.

Wednesday, November 14, 2012

Unit Testing your JavaScript

According to John Resig and Bear Bibeault 48% of JavaScript developement (see chapter 2, Secrets of the Java Script Ninja) do not test.  The advantages of unit testing code and developing in a test driven approach have been well documented and don't need to be rehashed - suffice to say the arguments are equally applicable to JavaScript code.  One popular approach to unit testing JavaScript is the QUnit framework. This framework was originally built to test JQuery and then evolved into a stand alone unit testing option for JavaScript in its own right. Let's consider an example. Suppose we have an architecture where the Web Tier makes AJAX REST style requests to a server and gets back information about entities in JSON format. It is probable that we will want to adapt the data that comes back into custom JavaScript objects that we can send on to various parts of the GUI. To convert the data, we use something similar to the GOF Adapter pattern. We collate methods involved in adapting different entities and then place them all in an object literal as follows:
var dublintech = dublintech || {};

// dataAdapter contains some functions to convert data.
// Idea is this can map JSON results from REST requests 
// to JavaScript formats the GUI expects.
dublintech.dataAdapter = {
    adaptStudents : function (data) {
        var adaptedStudentsVar = {
            students:[]
        };
  
        jQuery.each(data.students, function(indx, originalStudent){
            var student = {
                name: originalStudent.firstName + " " + originalStudent.lastName,
                dateOfBirth: originalStudent.dateOfBirth,
                nationality: originalStudent.nationality
            };
            adaptedStudentsVar.students.push(student);
        });
        return adaptedStudentsVar;
    },
 
    adaptHumans : function (data) {
       // ...
       // code to adapt humans
    },
 
    adaptAnimals : function(data) {
       // ...
       // code to adapt animals.
    }
};
This approach achieves a separation of concerns and is a good attempt at making things follow a stateless and functional paradigm.  
Note 1: Yes the above example is super simple. The only adaptation that is really happening is that the adpated name variable is made up from combining the first name with the last name that are in the JSON. The real world is obviously a more complicated place, but this simple adaptation example is enough to show how things hang together using QUnit.
Note 2: If you are wondering why I did not use a closure above, it is because there is no need for any state in these methods, hence there is no need to encapsulate any state. But again, in the real world you may not find it so easy to avoid state and if it comes you are better off encapsulating it using a closure.

And now the tests...

Ideally you'd like if:
  • any required testing libaries were taken from a public CDN.
  • your tests are 100% separate from your JavaScript code and have no impact your original source code.
  • your tests are easy to run and even easier to get results from.
To use the QUnit approach we simply write some JavaScript using the QUnit APIs in a HTML page. See below:
<html>
<head>
  QUnit basic example
  
  
  
  
</head>
<body>
  
<!-- test code </body> </html>

Now the salients points:
  1. The test exists in a separate file. It creates some test data, passes it to the adaptStudents method and checks that what is returned is what it should be.
  2. The JavaScript which contains the code that is being tested can be located anywhere that can be accessed by a HTTP request. So your test code does not have be located on the same machine / building as the JavaScript it is testing.
  3. The QUnit, JQuery libraries are pulled in from a CDN. 
  4. The test() API is a QUnit API which does exactly what it says  - that there is a test to execute!  There can be multiple tests() in the same file and they can be grouped using the module() API.
  5. equal() is a QUnit API which performs the actual test. QUnit has other assertion APIs (ok() and deepEqual()).
  6. It's simple to run this test. Just access this page in a web browser.
When the test is run, you get a picture like this:
Results
The results contain the following checkboxes
  • Hide passed tests - useful when you want to focus only on tests that failed
  • Check for globals - when selected QUnit will make a list of all properties on the window object, before and after each test and will check for differences. If properties are added or removed, the test will fail. 
  • No try/catch - If your test throws an exception, the testrunner will die, unable to continue running and will you will get the a  "native" exception. This can help debugging old browsers with bad debugging support like Internet Explorer 6.
The results page also contain the user agent used to run the tests (useful for screen shots), the total number of tests ran, the success summary and the overall execution time.  Each test is then detailed - including the number of failures, the numbers of success and the number of asserts in the test i.e. in this case (0, 3, 3).  You can also specify the number of assertions in a test and if they are not all invoked, the test will fail.

Anything else? 

Yes, QUnit can be used to test Asychronous code.  There are special APIs to indicate asynchronous code is being tested. QUnit can also test user interaction by leveraging JQuery trigger APIs.

What about mock objects?

There is no support for mock objects out of the box. However, there are a number of frameworks such as mockjax and sinjo.js  (in fact sinon.js has special support for QUnit).
Finally, I have put the source code detailed above on my Github.

Sunday, September 23, 2012

Is Java Dead or Invincible?


Is Java Dead?

Writer Isaac Asimov once said that "the only constant is change".  That isn't just a phrase in the software industry, it is an absolute fact.  Once, there was a day when Corba was king but it was usurped by Web Services.  Even within the world of Web Services, that used to be all about SOAP but now it's REST style services which are much more popular today.  Now somethings will obviously hang around a bit longer than others.  Relational databases have been around 40 years and aren't going to be kicked out by NoSql just yet. The HTTP protocol has been at version 1.1 since 1999 and has helped us use a thing called the Internet.  As for Java well that has been a pretty popular computer programming language for the last decade and a half.

According to Dutch research firm Tiobe in terms of overall popularity, Java ranked 5th in 1997, 1st in 2007 and 2nd in Sept 2012. At the time of writing there are over 2,000 Java progamming books on Amazon in English and there are almost 300,000 threads on Stackoverflow related to Java.   However, as George Orwell once said: "Whoever is winning at the moment will always seem to be invincible". But is Java invincible or beginning to die?  That's the question being asked more and more now.

In my humble opinion, the challenges to Java can be split into three categories:
  1. The rise of alternative languages
  2. Scalability / Multi-Core processors
  3. The return of the fat client.
Let's elaborate...

The rise of alternative languages

Alternative languages can be split into two groups: those that run on the JVM (Scala, Groovy etc)
and those that don't (Python, Ruby).  One interesting thing is that the first group is pretty large.  The languages that run on the JVM aren't mutual exclusive to Java and in a sense strengthen it reminding us what a remarkable piese of software engineering the JVM is.  Development teams can get that
extra bit of expressiveness in a niche language like Groovy, but can still call out to Java when they need some cool Java library or just need that extra bit of performance.  Remember the advantages in Groovy 2.0 speed it up but it is still not as fast as Java.

As for the features some of these languages provide that are not in Java, well that is the case but it won't always be the case.  Take a look at the roadmap for Java 8 and the features it will include. Just like Java EE 5 and 6 took ideas from Spring / Seam,  the Java lanuage in its 8th major release will be taking ideas from other languages. For example literal functions will be facilitated by Lambdas.  Java 8 Lamdas will have support for type inference and because they are just literals it will be possible to pass them around (and return them) just like a String literal or any anonymous Object.

That means instead of having to write an implementation of Comparator to pass to the Collections sort utility to sort a list of Strings, in Java 8 we will just do:
Collections.sort(list, (s1, s2) -> s1.length() - s2.length());

So, the alternative JVM languages don't exactly kick Java out of the party. It is still there, but in a party that has a better selection of music played and in a party where the guests encourages their host to be a better host.

Scaling on the multi-core platforms

As for multi-core and JVM - we all know that with a JVM running on a single core it was possible to spawn threads in the very first release of Java.  But these threads weren't executing in parallel, the CPU switched between them very quickly to create the impression that they were running in parallel. JStack may tell you that 50 threads have state "runnable" on your single core machine but this just means they are either running or eligible to run.  With multi-core CPUs it is possible to get true parallelism.  The JVM decides when to execute threads in parallel.

So what's the deal here?  Firstly, even though concurrency and threads were a feature of Java from the very beginning the language support was limited meaning development teams were writing a lot of their own thread management code - which could get ugly very quickly. This was alleviated greatly in JDK 1.5 with the arrival of a range of thread management features in the java.util.concurrent package.  Secondly, to get better parallelism something else was needed.  This came in Java 7 with Doug Lea's Fork / Join framework which uses clever techniques such as work stealing and double sided queues to increase parallelism. However, even with this Framework decomposing (and re-arranging) data is still a task that is needed to be done by the programmer.

Functional progamming gives us another option to perform computations on data sets in parallel.  
In Scala, for example, you just pass the function you wish to operate on the data and tell scala you want the computation to be parallelised.
outputAnswer((1 to 5).par.foreach(i => longComputation))

And guess what? The same will be available in Java 8.
Array.asList(1,2,3,4,5).parallel().foreach(int i ->heavyComputation())
Since scalability and performance are architectural cousins, it is worth stating that in many experiements Java still out performns other languages.  The excellent Computer Language Benchmark Game shows Java outperformaning many languages. It hammers the likes Perl, PHP, Python3, Erlang in many tests, beats Clojure, C# in nearly all tests and is only just behind C++ in terms in the performance results. Now,  performance tests can't cover everything and a context will always have some bias which favours one language over another but going by these tests it is not as if Java is a slow coach.

The fat client is back!

The return of the fat client

Since the advent of AJAX, Doug Crockford telling people how to use JavaScript and the rise of an excellent selection of JavaScript libraries the fat client is truely back.  Close your eyes and imagine what a cool single page web application such as gmail would look and feel like if it was just thin client web framework based on Spring MVC, JSF or Struts - you just cannot beat the performance of a well designed fat client.

One saving grace is that JavaScript is a lot more difficult to be good than some people think. It takes a lot more thinking to really understand  Closures, Modules and the various JavaScript best practises than it does to know your way around a web framework like Spring MVC and Struts. In addition, building a single page web application (again such as gmail) doesn't just require excellent JavaScript understanding it requires understanding of how the web works. For example, browsers don't put Ajax requests in the browser history.  So you gotta do something smart with fragment identifiers if you want the back and forward buttons to be usable and meaningful for the User.

There is a probably some room here for a hybrid approach which uses both a web framework and JavaScript and of course some JavaScript libraries.   This gives developers a structure to build an application and then the opportunity to use JavaScript, JQuery or whatever cool library takes there fancy for important parts of the Application that need to be jazzed up.   In a true fat web client approach, there should be no HTML served from the server (that means no JSPs), the only thing coming back from the server is data (in the form of JSON). However,  using a hybrid approach you can make a transition from thin to fat easier  and you can still put your JavaScript libraries on a CDN, you just won't get all the advantages of a full fat web client approach.

Summary

In summary, Java has had some bad moments. AWT was a rush job, Swing had performance problems, the early iterations of  EJB were cumbersome and JSF was problematic in comparison to other frameworks such as Struts and Spring MVC.  But, even today, extremely innovative projects such as Hadoop are built using Java.  It still has massive support from the open source community. This support has not only helped Java but also show Java some its problems and things it needs to get better at.   Java has shown it has the ability to evolve further and while other languages challenge it I don't think the game is over just yet.  It goes without saying, a lot will of the future of Java will depend on Oracle but let's hope whatever happens that the winner will be technology.

References

  1. Yammer and their migration to scala
  2. James Gosling taking about the state and future of Java at Google tech talk
  3. Article from Oracle describingFork and Join in Java 7
  4. Eric Bruno:Building Java Multi-Core applications
  5. Edgardo Hernandez:Parallel processing in Java
  6. IEEE top ten programming languages
  7. JDK 8 downloads
  8. Java Code Geeks article on Fork Join
  9. Good Fork Join article by Edward Harned
  10. Fork / Join paper from Doug Lea
  11. Fork / Join Java updates information from Doug Lea
  12. Scala Java Myths - great article by Urs Peter and Sander van der Berg

Monday, August 6, 2012

Make that form for User friendly!

I am reading the jQuery Cookbook at the moment. I will blog some interesting examples that I am come across and pad them out - if even only slightly - in the hope that they make more sense to the untrained eye. Let's begin! Consider a form as such:

Who is going to win the Heineken cup next year?

Click on any one of the teams, notice that the radio box is selected. Then start typing in the "Other" text box. Isn't it a bit odd that the team you previously selected is still selected even though you clearly started typing in the "Other" textbox? Does the user seriously have to explictly select the "other" radio button even though an "other" indication has already been given? Now, try this. Clear out the "other" text box and select another team. Then select the "other" radio button. Notice that the "other" textbox does not have focus even though you are hardly going to click the "other" check box and not want to type anything into the corresponding text field. Good GUI should assume the user will want to behave rationally. When the "Other" radio box is selected, it makes sense that its adjacent text box should get focus. Remember good usability means the user can achieve what they want with less clicking. And remember, good usability means that things are intuitive and GUIs do not display contradictions. So with all that in mind, we can include the discussed usability guidelines and come up with something like this:

Who is going to win the Heineken cup next year?

So how did we do that? Well let's take a look at code:

Discussion:

  1. :text is a JQuery psuedo class Selector which selects all elements of type text. As per JQuery recommendations, pseudo class Selectors should be preceded with another selector or tag element otherwise the universal selector is implied. In this case we do input:text and only one text box will be selected. That's ok.
  2. The .each(function(){ means iterate overall inputs of type text and execute the specified function. Don't forget ".each" can operate on sets of elements of any size including just 1 which is the case in this example.
  3. $(this) corresponds to the object which is being operated on by each. In this case it is each input text box. If you don't believe me add:

    
      console.log("this is: " + $(this)[0].id);
    
    

    and you will see something like:

    this is: Source5Txt in the console.

  4. The inputText button and radio button are stored in the local context. This is for efficiency.
Til the next time take care of yourselves.

Sunday, August 5, 2012

How JQuery changed events...

Event handling helps to enrich any application and that most definitely includes web applications. Do this when the button is clicked! Do this when the page has finished loading! Client side JavaScript has a range of event handling options. Before the days of funky JavaScript libraries such as JQuery, when the web was in its embryonic stage, event handling was achieved purely in JavaScript. One technique was to set the event handling properties to some JavaScript code. For example:
...


Here the onclick event property is set so that the an alert message is shown when the button is clicked. The Window object, Document node and the various Element objects all have a selection of event properties. Some of the more interesting ones are:
  • window.unload - triggered when user is navigating away from from a document.
  • form.onchange - can be used to capture a change from any element in the form thru a technique known as bubbling.
  • element.onload - every document element (e.g. ,
All seemed much nicer, but IE complicated things:
  1. IE8 did not support addEventListener(). Instead you had to use attachEvent()
  2. Event handlers usually receive an Event object (http://www.w3schools.com/jsref/dom_obj_event.asp) which contains details of the event. This will contain properties such as the element that trigged the event, the name of the event and the time it was created etc. To receive this event simply add it to the event handler.
    button.addEventListener("click", function(event) {
        alert("You clicked me with an event of type!" + event.type)}, false);
    
    But you guessed it, IE8 did not support this mechanism to get details of the event and instead, you had to check the global variable window.event to get information about it. This lead to messy JavaScript code such as
    function handler(event) {
        event = event || window.event;  // got to cater for Microsoft!
    }
    
  3. The "this" keyword in the event handling code usually referred to the document element that fired the event. However in IE8's attachEvent(), the this referred to the global window.
JQuery comes to the rescue providing APIs that work in all browsers. The commonly used events (e.g click, load) have their own event registration APIs (click(), load()). Similar to JavaScript's addEventListener() the JQuery event handler APIs allow multiple event handling logic to be associated with the same event. And similar to JavaScript, JQuery event handler functions do not have to have arguments or return values but both are supported. The value add being that JQuery APIs work and all browsers - that means event objects are passed into event handlers for poor old IE8!
//add to all button elements
$("button").click(function() {alert("You clicked me");}); .
So JQuery clearly solves some problems here. Does it offer anything else? Of course... the bind() API. This allows:
  • the same handler to be executed for multiple events. Just separate the events by a space.
    // invoke myEventHanlder for any click, mousedown events for any div elements.
    $('div').bind('click mousedown', myEventHandler);  
    
  • the same handler function to be reused with different data. This is achieved by passing an Object literal as the second object in the bind API. The object literal values can then be read in the event handler via the event objects data properties.
    // call buttonClicked and pass color red to it.
    jQuery('#button1').bind('click', {team:'Leinster'}, buttonClicked);
    // call the same buttonClicked function but pass blue. 
    jQuery('#button2').bind('click', {team:'Munster'}, buttonClicked); 
    
    buttonClicked function could then be something like:
    function buttonClicked(event) {
        alert("you selected team" + event.data.team);
    }
    
  • Refer to multipe event handlers at the same time. This is achieved in JQuery by using namespaces for the events. Suppose you want to group a selection of events. You could put them all into the same namespace click.myclickevents.
    $("#myButton1").bind('click.myclickevents', myfunction());
    $("#myButton1").bind('mousedown.myclickevents', myfunction());
    
  • Because they are grouped they can be reffered to now at the same time. This comes in handy if you want to remove them.
    $("#myButton1").unbind('myclickevents');
    
In addition JQuery provides:
  • The one() API. This is similar to bind, except the eventhandlers only get called once. They are then deregistered.
  • The trigger() API. This provides the ability to manually cause event handlers (including custom events) to be invoked.
  • Live events This is like the event handling achieved with the bind() except it will also add event handling logic to new elements that are to still to be created, whereas bind() only adds it to existing elements.
The End?

Not quite. In order to stop people getting confused about the various JQuery event handling APIs JQuery unified them all into one API, the on() API. See also 1.7 release notes.

Saturday, August 4, 2012

Book Review: Even Faster Websites (Steve Souders)

Author Steve Souders (Head Performance Engineer at Google, previously Chief Performance at Yahoo) grew to fame with the YSlow Firefox plugin - a super little gizmo which gave web developers all sorts of ideas for how to speed up their web sites. The book 'High Performance Web Sites: Essential Knowledge for Front-End Engineers book' elaborated on everything the YSlow plugin was telling you. That book effectively serves a forerunner to 'Even Faster Web Sites'. In fact there is an assumption the reader has already read it, is already familiar with all the points it made and is now prepared to dig deeper.  Anyone with an interest in performance is in for a treat with this little gem.



I thought 'Even Faster Web Sites' detailed many clever techiques to boost performance. Amongst some of my favourites:
Steve Sounders
  • Create a <script> element and set its src attribute to a JavaScript file you want to download asychronously.
  • Use the script onload's event - which will only be called when the script has finished downloading - to avoid race conditions.
  • Succint explainations on how deep scope chains in JavaScript can degrade performance
  • Tips on when to use if statements, switch statements and arrays for flow control.
  • A good overview of the Comet Architectural approach and how it can be achieved.
  • Domain sharding tips: split based on resource type e.g put CSS and images on one domain, everything else on another domain.

There are also timely reminders, including:
  • That IFrames make it easy for the UserAgent to print part of a page and are a mechanism to split part of your document giving it independent characteristics.
  • IFrames are more expensive to download.
  • That a browser's busy indicator stops once the Window.onLoad event is fired.
  • Some browsers have limits on how long the JavaScript engine can run
  • Web proxies and security software can mangle the Accept-Encoding header of request so that they speed up their screening of the response from the web server in a process Souders refers to as Turle Tapping.
  • Browsers enforce their maximum connections per server rule based on the hostname in the URL not the IP address it resolves to.
  • That CSS selectors work in a "rightmost first" fashion.
It is a super book. Not just to get ideas to boost web performance but because it helps deepen architectural understanding of the web. There are many important parts in the Web tier: all the different resource types, sychronous / asychronous processing, the various ways blocking can happen, a very sophisticated object model, a funny old language by the name of JavaScript and of course the endless list of quirks from different browsers. There was a time when everything revolved around the database but now a deep understanding web is probably more important. This book most definetly helps deepen understanding of the Web Tier.

Tuesday, July 24, 2012

Are you leaving my site?

A website will always contain some links. Links fall into one of two categories:
  1. Internal links - links to other parts of your website.
  2. External links - links to other websites external to your website.

There are times when it might make sense to warn the user you are leaving your site. For example, you may have a SAAS style architecture with external links. It is good usability to differentiate links that keep the user on the site and links which will take the user away from the site especially if the latter could invalidate a transaction or session. Even if nothing could become invalidated it must just to differentiate in cases when the site the user will be trvalleing to next is very similar (which might lead the user to think it is the same site), or it might just be nice to say bye.

Well one way you could do this is to use some JQuery to select to all external links and add some JavaScript to execute to warn the user of the results of their action.

Check it out...



Try it out... An explanation of the code:
  • a[href^='http:'
    The ^ after href means means all elements that begin exactly with http:. This is an example of how JQuery builds on CSS selectors.
  • :not([href*='"+location.hostname+"'])
    means match elements that do not match the window.location.host property. Don't forget jquery provides many powerful selection filter expressions using the (:) syntax, Other examples are :first, :odd and :even.
  • ... location.hostname
    is the dom way of figuring out the hostname of your site.
  • attr("target","_blank")
    is a browser standard to open a new window.
  • .click
    is the JQuery method whichs binds custom event handler to the the JavaScript "click" event.

Sunday, June 24, 2012

Book Review: Essential Software Architecture (2011 edition)

This book begins by defining what software architecture is - a term that can be mean different things to different people and different organisations. It then explains all the various non-functional requirements (performance, scalability, security etc) things that I think everyone would agree are very important in software architecture. It then explains various architectural approaches used in enterprise systems. This includes web services, message orientated systems, model driven architecture, aspect orientated architectures. There is also a case study which shows how some of concepts described can be applied.

My favourie part was on message orientated architectures. All the fundamental and sophisticated aspects are very explained. These include: the asychronous nature of message systems, the way you can cluster message ques and brokers, the hierachial naming formats in publish subscribe message topics and the different approaches to reliability (best effort, persistent and transactional). There was also some really good discussion regarding the background and importance of message brokers.

As well as technical concepts there are also some interesting sections on architectural processes, documentation and even my old favourite UML!

This book serves as a very good reminder to the importance of software architecture - especially in enterprise systems. Architectural approaches don't just need to be properly understood, they need to be compared with other approaches especially with respect to the non-functional requirements that are important to your system.

Ian Gortan
Ian Gortan is a super writer. His style is very succint, concise  and erudite.  It would be very interesting to hear his opinions on various Big Data / NoSql options, the return of the fat client and explosion of JavaScript usage and what the key points are in all this are for software architects.  I would recommend this book to any developer, architect or anybody with an interest in the key concepts of enterprise systems.

Thursday, May 24, 2012

Book Review: 'Scalability Rules: 50 Principles for Scaling Web Sites'

I absolutely love Technical Architecture. It is something that requires high standards in engineering to do well.  In 'Scalability Rules', Martion Abbott and Michael Fisher detail 50 tips, where each tip communicates a simple or sophisticated idea in a few short pages. Their ideas are based from real world experience of working with over 200 internet architectures.

Performance and its cousin Scalability are always an important part of any software architecture and while some cynics will say some of the tips in this book are common sense, there's plenty of really good advice that if adhered to would certaintly lower the probability of scalability issues which are nearly inevitable at some stage in the life of a project.

Among my favourites tips:
  • Put Object caches on their own tier. This makes it easier to size their hardware needs - object caches typically need a lot of memory. It it easier to organise and control this when they have their own tier.
  • Pass on multi-phase commits if possible as they are difficult to scale.
  • Smart reminders such as when it is really important to use aschronous models (integrating with 3PP frameworks, when there is a temporal constraint etc).
I wouldn't just recommend individuals to read this book, I would recommend teams read it. Some important ideas such as spliting up system processing by something like customerId are given concrete names such as Z-Axis splits. The would help teams speak start speaking the same language when communicating ideas. It would also help to remind teams that some simple things such as using logfiles, monitoring your system properly and not relying on QA to find faults that should be found earlier are very important and should not be forgotten.

In summary, there are not too many good books on software architecture and this is certainly one of the best I have read. I have already read parts of it 3 times and I am sure I will be referring to parts of it again.

Book Review: 97 things every Software Architect should know


You can't judge a book by its cover but you can certainly ask questions about its title. Why '97 things every Software Architect should know'? Why not 98, 99 or even 100? Well the word on infoq is that they wanted a number near 100 so that there would be enough material for a reasonably sized book. Fair enough so... The book contains 97 articles published by a range of software professional expressing their views on various aspects of software architecture. Many of the articles are not very technical in nature and there are - perhaps - a lot of similarities between this book and '12 Essential Skills for Software Architects' where author Dave Hendricksen focusses on non-technical skills essential to be a succseful architect. Other articles probably aren't just things an Architect should know but really things anyone working in Software Engineering could benefit from knowing and thinking about. I even include Project Managers in that!

That said, there are some really enjoyable bits and pieces. My favourite parts:
  • Keith Braithwaite's reminding of the architect's need to quantify things. Characteristics such as average response time should be not be phrased using terms such as 'good' or 'satifactory' but quantified as something like: 'between 750ms and 1,250ms'
  • Craig Russell's points about including the human interaction time in any performance analysis. The system may respond very fast to API calls, but the if the UI is counter-intuitive, it means the user will spend a longer time try to get his result.
  • Michael Nygard advice for engineering the 'white spaces'. Don't just have arrows between components specifying the communication protocol, describe the performance expectation of interaction e.g. 100 requests per second, response time 250ms 99% of time. Describe how the system will handle overload, bad response times, unavailability etc.
  • Mark Richards classification of architectural patterns:
    • Enterprise Architecture Patterns: EDA, SOA, ROA, Pipeline architecture
    • Application Architecture: Session Facade, Transfer Object
    • Integration Patterns: File sharing, RPC, Messaging
    • Design Patterns: GoF
  • Gregor Hohpe arguments about the 'predictive call-stack architecture' becoming a thing of the past.
    In massive distributed systems, it's not so easy to define the order things happen in. Architectures now have to be able to respond to events in any time order.
  • Bill de hOra discussion of inevitable tradeoffs using Brewer's conjecture (CAP) as an example.
  • Dave Anderson's arguments for the inevitabitly of legacy and preparing your system for maintenance.
So plenty of good advise in a short book that never gets too technical. The role of the architect is not just to be capable of understanding complicated problems but to stand back and look at the big picture, checking for gaps and to ensure the right actions are taken to ensure project success. This means it's not really just about things a software architect should know, but about things a software architect should ensure they never forget. 

Tuesday, May 22, 2012

Book review: 'Are you smart enough to work at Google?'

You need to toss a coin for a football match. The only coin you have is bent and biased towards one outcome. How do you use the coin and ensure a fair toss?

I love a good a puzzle and there are certainty plenty of thought provoking mind benders in this book - most of which I had not heard before. Author William Poundstone (author of 'How Would You Move Mount Fuji' and 'Fortune's Formula') describes various puzzles that are describes various puzzles that are likely to be part of a Google interview process - that company now estimated to be running over one billion search requests per day!  Some other aspects of Google are covered, but the subject matter is predominately puzzles - all types of puzzles: fermi questions, deductive logic, numeracy skill, algorithmic questions and some grade A counter intuitive mind boggling teasers!

William Poundstone
One can't help asking the question why Google bothers with all of this?  Surely, the point of an interview is to see if someone can do a certain type of work and the interview should be a fair attempt to assess a candidate's suitability. I have had the fortune (some would say misfortune) to be part of world of Software engineering for the last 15 years.  I am passionate about it, but I'll be the first to admit it isn't just about solving fun puzzles. Following best practises, following agreed processes, keeping up to speed with technology, documenting solutions so others can see what's going on are all very important things to make a good software engineer.  And it's not always sexy work.  Sometimes it requires patience  debugging ugly code while sticking to a tight project deadline. Ascertaining how good someone is at all this in an interview setting can be difficult - especially when it's very easy for a good candidate to freeze from nerves or get an unexpected mental block.  It's very difficult to objectify what makes a good software engineer. Sometimes someone very intelligent can get hung up on abstractions or theoritical patterns and forget they have deadlines or just not be a good team player.  Sometimes, there's just inescapable subjectivity.

Joel Spolksy
So how do brain teasers help out? Acclaimed tech guru, Joel Spolsky advises to avoid asking them in interviews because they are usually just a case of either the candidate knows it or he doesn't - and not much else.  In my opinion, it can take months to understand someone's technical strengths and weaknesses.  Puzzles can be useful for demostrating how someone approaches problem solving, how they think on their feet and how they communicate ideas.  So yes they do serve a purpose.  But even if they serve no purpose whatsoever other than a bit of fun, that's fine for me.  I love a good puzzle so I really enjoyed this book and for that reason I'd recommend it to anyone who likes to dabble in some cryptic challenges.

References:
1.  Are you smart enough to work at Google

Sunday, April 1, 2012

JavaScript language a- z cheat sheet

Here is an A - Z list of some Javascript idioms and patterns. The idea is to convey in simple terms some features of the actual Javascript language (rather than how it can interact with DOM). Enjoy...

Array Literals
An array literal can be defined using a comma separated list in square brackets.
var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 
                     'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
console.log(months[0]); // outputs jan
console.log(months.length) // outputs 12

Arrays in javascript have a wide selection methods including push() and pop().  Suppose the world got taken over by a dictator who wanted to get rid of the last month of the year? The dictator would just do...
months.pop();
And of course, the dictator will eventually want to add a month after himself when everyone will have to worship him:
months.push("me");

Callbacks
Since functions are objects, they can be passed as arguments to other functions.
function peakOil(callback) {
    //... code
    callback();  // the parentheses mean the function is executed!
}

function changeCivilisationCallback(){
   //... 
}

// Now pass the changeCivilisationCallback to peakOil.
// Note: no changeCivilisationCallback parentheses because it is not 
// executed at this point.
// It will be excuted later inside peak oil.
peakOil(changeCivilisationCallback); 
In the example above, the chanceCivilisationCallback callback function is invoked by peakOil. Logic could be added to check if the energy returns from solar panels and wind farms were sufficient in which case another callback, other than changeCivilisationCallback could be added.

Configuration Object 
Instead of passing around a bunch of related properties...
function addCar(colour, wheelsize, regplate) {...}
Use a configuration object
function addCar(carConf) {...}

var myCarConf = {
    colour: "blue",
    wheelsize: "32",
    regplate: "00D98788"
};
addCar(myCarConf);
The use of a configuration object makes it makes it easier to write clean APIs that don't need to take a huge long list of parameters. They also means you are less likely to get silly errors if parameters are in the wrong order.
Closures
There are three ways to creats objects in Javascript: using literals, using the constuctor function and by using a closure.  What closures offer that the other two approaches do not is encapsulation.  Closures make it possible to hide away functions and variables.
var counter = function(count) {
    console.log(">> setting count to " + this.count);
    return {
        getCount: function(){
           return ++count;
        }
    }
}

mycounter = counter(0);
console.log(mycounter.getCount());  // outputs 1
console.log(mycounter.getCount());  // outputs 2
console.log(mycounter.getCount());  // outputs 3
console.log(mycounter.getCount());  // outputs 4

// Same again with offset this time.
mycounterWithOffset = counter(10);
console.log(mycounterWithOffset.getCount());  // outputs 11
console.log(mycounterWithOffset.getCount());  // outputs 12
console.log(mycounterWithOffset.getCount());  // outputs 13
console.log(mycounterWithOffset.getCount());  // outputs 14

Note: The closure is the object literal returned from annoymous function. It "closes" over the count variable. No-one can access it except for the closure. It is encapsulated. The closure also has a sense of state. Note also how the it maintains the value of the counter.  

Constructor Functions (Built in)
There are no classes in Javascript but there are construtor functions which use the new keyword syntax similar to the class based object creation in Java or other languages. Javascript has some built-in constructor functions. These include Object(), Date(), String() etc.
var person = new Object();  // person variable is an Object
person.name = "alex";  // properties can then be dynamically added

Constructor Functions (Custom)
When a function is invoked with the keyword new, it is referred to as a Constructor function. The new means that the new object will have a hidden link to value of the function's prototype member and the this keyword will be bound to the new object.
function MyConstrutorFunction() {
    this.goodblog = "dublintech.blogspot.com";
}
 
var newObject = new MyConstrutorFunction();
console.log(typeof newObject);    // "object"
console.log(newObject.goodblog);  // "dublintech.blogspot.com"

var noNewObject = MyConstrutorFunction();
console.log(typeof noNewObject);  // "undefined"
console.log(window.tastes);       // "yummy"
The convention is that constructor functions should begin with a capital letter. Note: if the new keyword is not used, then the 'this' variable inside the function will refer to the global object. Can you smell a potential mess? Hence why the capital letter convention for constructor functions is used. The capital letter means: "I am a constructor function, please use the new keyword".

Currying 
Currying is the process of reducing the number of arguments passed to a function by setting some argument(s) to predefined values. Consider this function.
function outputNumbers(begin, end) {
    var i;
    for (i = begin; i <= end; i++) {
        print(i);
    }
}
outputNumbers(0, 5);  // outputs 0, 1, 2, 3, 4, 5
outputNumbers(1, 5);  // outputs 1, 2, 3, 4, 5
Suppose, we want a similar function with a fixed "begin" value. Let's say the "begin" value was always 1. We could do:
function outputNumbersFixedStart(start) {
    return function(end) {
        return outputNumbers(start, end);
    }
}
And then define a variable to be this new function...
var outputFromOne = outputNumbersFixedStart(1);
outputFromOne(3);  1, 2, 3
outputFromOne(5);  1, 2, 3, 4, 5

Delete Operator
The delete operator can be used to remove properties from objects and arrays.
var person = {name: 'Alex', age: 56};
// damn I don't want them to know my age remove it
delete person.age;
console.log("name" in person);  // outputs true because it is still there
console.log("age" in person);   // outputs false


var colours = ['red', 'green', 'blue']
// is red really in the array?
console.log(colours.indexOf('red') > -1);  // outputs true. 
// remove red, it's going out of fashion!
delete colours[colours.indexOf('red')];
console.log(colours.indexOf('red') > -1);  // outputs false
console.log(colours.length) // length is still three, remember it's javascript!

You cannot delete global variables or prototype attributes.
console.log(delete Object.prototype)  // can't be deleted, outputs false
function MyFunction() {
    // ...
}
console.log(delete MyFunction.prototype) // can't be deleted, outputs false

var myglobalVar = 1;
console.log(delete this.myglobalVar)   // can't be delete, outputs false


Dynamic Arguments
Arguments for a function do not have to be specifed in the function definition
function myFunction(){
   // ... Note myfunction has no arguments in signature
   for(var i=0; i < arguments.length; i++){
       alert(arguments[i].value);
   }
}

myFunction("tony", "Magoo");  // any argument can be specified
The arguments parameter is an array available to functions and gives access to all arguments that were specified in the invocation.

for-in iterations
for-in loops (also called enumeration) should be used to iterate over nonarray objects.
var counties = {
    dublin: "good",
    kildare: "not bad",
    cork: "avoid"
}

for (var i in counties) {
    if (counties.hasOwnProperty(i)) { // filter out prototype properties
        console.log(i, ":", counties[i]);
    }
}

Functions are literals
This is an important one for people coming from a Java background. Functions do not need to have names. They can be anonymous, they can be passed into and returned from other functions without any needing a name - they can be treated literally. When a Java developer sees a function, they can't help thinking they are analogous to Java methods. But, Java methods can never be anonymous, they can be never be passed to or returned from other methods. They can be wrapped in an anonymous object defined on the fly; but they need that object that in many cases does nothing else - the methods themselves can never be treated literally. JavaScript ability to treat functions literally gives it a lot of expressive power.

Function declaration
In a function declaration, the function stands on its own and does not need to be assigned to anything.

function multiple(a, b) {
    return a * b;  
} // Note, no semi colan is needed 

Function expressions
When function is defined as part of something else's definition, it is considered a function expression. 

multiply = function multiplyFunction(a, b) {
    return a * b; 
}; // Note the semi colan should always be placed after the function

console.log(multiply(5, 10)); // outputs 50

In the above example, the function is named.  It can also be anonymous, in which case the name property will be a blank string.

multiply = function (a, b) {
   return a * b; 
}; // Note the semi colan should always be placed after the function  

console.log(multiply(5, 10)); // outputs 50

Functional Inheritance
Functional inheritance is mechanism of inheritance that provides encapsulation by using closures. Before trying to understand the syntax, take an example first. Suppose we want to represent planets in the solar system. We decided to have a planet base object and then several planet child objects which inherit from the base object. Here is the base planet object:
var planet = function(spec) {
    var that = {};
    that.getName = function() {
        return spec.radius;
    };
    that.getNumberOfMoons()= function() {
        return spec.numberOfMoons;
    };
    return that;
}
Now for some planets. Let's start with Earth and Jupiter and to amuse ourselves let's add a function for Earth for people to leave and a function to Jupiter for people arriving. Sarah Palin has taken over and things have got pretty bad!!!
var earth = function(spec) {
    var that = planet(spec);   // No need for new keyword!
    that.peopleLeave = function() {
        // ... people leave
    }
    return that;
}
var jupiter = function(spec) {
    var that = planet(spec);  
    that.peopleArrive = function() {
       // .. people arrive
    }
    return that;
}
Now put the earth and jupiter in motion...
    
var myEarth = earth({name:"earth",numberofmoons:1});
var myjupiter=jupiter({name:"jupiter",numberofmoons:66});
The three key points here:
  1. There is code reuse.
  2. There is encapsulation. The name and numberOfMoons properties are encapsulated.
  3. The child objects can add in their own specific functionality.
Now an explanation of the syntax:
  1. The base object planet accepts some data in the spec object.
  2. The base object planet creates a closures called that which is returned. The that object has access to everything in the spec object. But, nothing else does. This provides a layer of encapsulation.
  3. The child objects, earth and jupiter, set up their own data and pass it to base planet object.
  4. The planet object returns a closure which contains base functionality. The child classes receive this closure and add further methods and variables to it.
Hoisting 
No matter where var's are declared in a function, javascript will "hoist" them meaning that they behave as if they were declared at the top of the function.
mylocation = "dublin"; // global variable
function outputPosition() {
    console.log(mylocation);  // outputs "undefined" not "dublin"
    var mylocation = "fingal" ;  
    console.log(mylocation);  // outputs "fingal"
}
outputPosition(); 
In the function above, the var declaration in the function means that the first log will "see" the mylocation in the function scope and not the one declared in the global scope. After declaration, the local mylocation var will have the value "undefined", hence why this is outputted first.  Functions that are assigned to variables can also be hoisted.  The only difference being that when functions are hoisted, their definitions also are - not just their declarations.

Immediate Function Expressions
Immediate function expression are executed as soon as they are defined.
(function() {

    console.log("I ain't waiting around");

}());
There are two aspects of the syntax to note here.  Firsty, there is a () immediately after the function definiton, this makes it execute. Secondly, the function can only execute if it is a function expression as opposed to a function declaration. The outer () make the function an expression.  Another way to define a an immediate function expression is:
var anotherWay = function() {
    console.log("I ain't waiting around");
}()

JSON
JavaScript Object Notation (JSON) is a notation used to represent objects. It is very similar to the format used for Javascript Object literals except the property names must be wrapped in quotes. The JSON format is not exclusive to javascript; it can be used by any language (Python, Ruby etc). JSON makes it very easy to see what's an array and what's an object. In XML this would be much harder. An external document - such as XSD - would have to be consulted. In this example, Mitt Romney has an array describing who might vore for him and an object which is his son.
{"name": "Mitt Romney", "party": "republicans", "scary": "of course", "romneysMostLikelyVoters": ["oilguzzlers", "conservatives"], son : {"name":"George Romney"}}

Loose typing
Javascript is loosely typed. This means that variables do not need to be typed. It also means there is no complex class hierarchies and there is no casting.
var number1 = 50;
var number2 = "51";

function output(varToOutput) {
    // function does not care about what type the parameter passed is.
    console.log(varToOutput);
}
output(number1);  // outputs 50
output(number2);  // outputs 51

Memoization
Memoization is a mechanism whereby functions can cache data from previous executions.
function myFunc(param){
    if (!myFunc.cache) {
        myFunc.cache = {}; // If the cache doesn't exist, create it.
    }
    if (!myFunc.cache[param]) {
        //... Imagine the code to work out result below
        // is computationally intensive.
        var result = { 
            //... 
        };
        myFunc.cache[param] = result;  // now result is cached.
    }
    return myFunc.cache[param];
}

Method
When a function is stored as a property of an object, it is referred to as a method.
var myObject { 
    myProperty: function () {
       //...
       // the this keyword in here will refer to the myObject instance.
       // This means the "method" can read and change variables in the 
       // object.
    }
}

Modules
The goal of modules is to enable javascript code bases to more modular.  Functions and variables are collated into a module and then the module can decide what functions and what variables the outside world can see - in the same way as encapsulations works in the object orientated paradigms. In javascript we create modules by combining characteristics of closures and immediate function expressions.
var bankAccountModule = (function moduleScope() {
    var balance = 0; //private
    function doSomethingPrivate(){  // private method
        //...
    }   
    return { //exposed to public
        addMoney: function(money) {
             //...    
        },
        withDrawMoney: function(money) {
             //...
        },
        getBalance: function() {
            return balance;
    }
}());
In the example above, we have a bank account module:
  • The function expression moduleScope has its own scope. The private variable balance and the private function doSomethingPrivate, exist only within this scope and are only visible to functions within this scope.
  • The moduleScope function returns an object literal. This is a closure which has access to the private variables and functions of moduleScope. The returned object's properties are "public" and accesible to the outside world.
  • The returned object is automatically assigned to bankAccountModule
  • The immediate function ()) syntax is used. This means that the module is initialised immediately.
Because the returned object (the closure) is assigned to bankAccountModule, it means we can access the bankAccountModule as:
bankAccountModule.addMoney(20);
bankAccoumtModule.withdrawMoney(15);
By convention, the filename of a module should match its namespace. So in this example, the filename should be bankAccountModule.js.  

Namespace Pattern
Javascript doesn't have namespaces built into the language, meaning it is easy for variables to clash. Unless variables are defined in a function, they are considered global. However, it is possible to use "." in variables names. Meaning you can pretend you have name spaces.
DUBLINTECH.myName = "Alex"
DUBLINTECH.myAddress = "Dublin" 

Object Literal Notation
In javascript you can define an object as collection of name value pairs.   The values can be property values or functions.
var ireland = {
    capital: "Dublin",
    getCapital: function () {
        return this.capital;
    }
};

Prototype properties (inheritance)
Every object has a prototype object. It is useful when you want to add a property to all instances of a particular object. Suppose you have a constructor function, which representent Irish people who bought in the boom.
function IrishPersonBoughtInTheBoom(){
}

var mary = new IrishPersonBoughtInTheBoom ();
var tony = new IrishPersonBoughtInTheBoom ();
var peter = new IrishPersonBoughtInTheBoom ();
...
Now, the Irish economy goes belly up, the property bubble explodes and you want to add a debt property to all instances of this function. To do this you would do:
IrishPersonBoughtInTheBoom.prototype.debt = "ouch";
Then...
console.log(mary.debt);   // outputs "ouch"
console.log(tony.debt);   // outputs "ouch"
console.log(peter.debt);   // outputs "ouch"
Now, when this approach is used, all instances of IrishPersonBoughtInTheBoom share the save copy of the debt property. This means, that they all have the same value as illustrated in this example.  

Returning functions
A function always returns a value.  If return is not specified for a function, the undefined value type will be returned. Javascript functions can also return some data or another function.
var counter = function() {
    //...
    var count = 0;
    return function () {
        return count = count + 1;
    } 
}

var nextValue = counter();  
nextValue();   // outputs 1
nextValue();   // outputs 2
Note, in this case the inner function which is returned "closes" over the count variable - making it a closure - since it encapsulates its own count variable. This means it gets its own copy which is different to the variable return by nextValue.count.

this keyword
The this keyword in Java has different meanings, depending on the context it is used. In summary:
  • In a method context, this refers to the object that contains the method.
  • In a function context, this refers to the global object. Unless the function is a property of another object. In which case the this refers to that object.
  • If this is used in a constructor, the this in the constructor function refers to the object which uses the constructor function.
  • When the apply or call methods are used the value of this refers to what was explictly specified in the apply or call invocation.
typeof
typeof is a unary operator with one operand. It is used to determine the types of things (a bit like getClass() in Java). The values outputted by typeof are "number", "string", "boolean", "undefined", "function", "object".
console.log(typeof "tony");          // outputs string
console.log(typeof 6);               // outputs number
console.log(typeof false);                  // outputs boolean
console.log(typeof this.doesNotExist);   // outputs undefined if the global scope has no such var
console.log(typeof function(){});    // outputs function
console.log(typeof {name:"I am an object"});  //outputs object
console.log(typeof ["I am an array"]) // typedef outputs object for arrays
console.log(typeof null)              // typedef outputs object for nulls
Some implementations return "object" for typeof for regular expressions; others return "function". But the biggest problem with typeof is that it returns object for null. To test for null, use strict equality...
if (myobject === null) {
    ...
}

Self-redefining functions
This is a good performance technique. Suppose you have a function and the first time it is called you want it to perform some set up code that you never want to perfom again. You can execute the set up code and then make the function redefine itself after that so that the setup code is never re-excuted.
var myFunction = function () {
    //set up code only to this once
    alert("set up, only called once");
   
    // set up code now complete.
    // redefine function so that set up code is not re-executed
    myFunction = function() {
         alert("no set up code");
    }
}
myFunction();  // outputs - Set up, only called once
myFunction();  // outputs - no set up code this time
myFunction();  // outputs - no set up code this time
Note, any properties added to the set up part of this function will be lost when the function redefines itself. In addition, if this function is used with a different name (i.e. it is assigned to a variable), the re-definition will not happen and the set up code will re-execute.

Scope
In javascript there is a global scope and a function scope available for variables. The var keyword does not need to be used to define variable in the global scope but it must be used to define variable in the local function scope. When a variable is scoped to a local function shares the name with a global variable, the local scope takes precedence - unless var was not used to declare the local variable in which case any local references are pointing to the global reference. There is no block scope in javascript. By block we mean the code between {}, aka curly braces.
var myFunction = function () {
var noBlockScope = function ( ) {
    if (true) {  
        // you'd think that d would only be visible to this if statement
        var d = 24;    
    }
    if (true) { 
        // this if statement can see the variable defined in the other if statement
        console.log(d);  
    }
}
noBlockScope();

Single var pattern
You can define all variables used by a function in one place.  It is ensures tidy code and is considered best practise.
function scrum() {
    var numberOfProps = 2,
        numberOfHookers = 1,
        numberOfSecondRows = 2,
        numberOfBackRow = 3
    // function body...
}
If a variable is declared but not initialized with a value it will have the value undefined.
Strict Equality
In javascript it is possible to compare two objects using ==. However, in some cases this will perform type conversion which can yield unexpected equality matches. To ensure there is strict comparison (i.e. no type conversions) use the === syntax.
console.log(1 == true)    // outputs true
console.log(1 === true)   // outputs false
console.log(45 == "45")   // outputs true
console.log(45 === "45")  // outputs false

Truthy and Falsey
When javascript expects a boolean, you may specify a value of any type. Values that convert to true are said to be truthy and values that convert to false are said to be falsey. Example of truthy values are objects, arrays, functions, strings and numbers:
// This will output 'Wow, they were all true'
if ({} && {sillyproperty:"sillyvalue"} && [] &&
        ['element'] && function() {} && "string" && 89) {
   console.log("wow, they were all true");
}
Examples of falsey values are empty strings, undefined, null and the value 0.
// This will out put: 'none of them were true'
if (!("" || undefined || null || 0)) {
    console.log("none of them were true");
}

Undefined and null
In javascript, the undefined value means not initialised or unknown where null means an absence of a value.

References
  1. JavaScript patterns Stoyan Stefanov
  2. JavaScript, The Definitive Guide David Flanagan
  3. JavaScript, The Good Parts Doug Crockford.