Author Archives: donyd

AngularJS Single Page Application (SPA)

So for my next quest, I’ve decided to go with a Single Page Application for the following reasons:

  • To start exploring JavaScript frameworks
  • Get some much needed interactivity on screen
  • Increase the complexity of the projects I am going after to move out of my comfort zone

I’ve decided to test the water with AngularJS. Why you might be asking? Well the previous mini project I completed was using PHP, and to further build on that language I chanced upon a course on pluralsight Building a Site with AngularJS and PHP. Since tacit conditions mean I can’t write about non JavaScript related builds, it made sense to do a crossover. Granted, I doubt I will be using a PHP/AngularJS combo for what entails.

The pluralsight tutorial was interesting but the nature of tutorial videos and instructor bias of students understanding and assimilating information at the same level as they proffer the instructions, means that certain aspects would be glossed over with the student being none the wiser.

So, in keeping with the familiar thread throughout my journey, one of the best ways to learn is to attempt to build something yourself. And after much head scratching the best thing I could think of doing was a simple to do list. Yes partly because I have been drawing blanks and the fact of using something I have almost no clue about is daunting to say the least. Also this is a priming exercise to test the waters, so something overly complex isn’t the end goal.

So I shall start with the minimal of outlays and setups and progress from there as usual. Check out my ‘awesome’ concept sketch. Mind blowingly simple.

To do list concept sketch

Caveat: AngularJS is the first version that was released with Angular 2 onwards being a complete rewrite of the framework. So pursuing AngularJS is pure curiousity and what’s transferable to learning Angular2+ (currently Angular6 beta) might only be an exercise in comparative analysis.

What’s this? Second Anniversary for JavaScript: ‘Unscripted’

It seems the the world has gone around the sun completely once again. And this happens to be the two year mark for JavaScript: ‘Unscripted’.

A lot has happened since last year. The last few months were pretty hectic in more ways than one, which meant not a lot of work could be done on this blog. Just finished up a simple weather app today but since it was done in PHP (shh, not so loud) a write up didn’t happen here. See the app in action here weatherGetter [simple app, simpler name see git repo if you’re so inclined].

But all is not lost, it’s all part of the plane. One of which is to iterate on the design/functionality of this blog, which, surprise surprise, is built on PHP. Another facet of that is launching a sub-site which will focus on all matters which are not specifically JavaScript.

So here’s to another great year which will:

  • Push harder on the route to JavaScript mastery
  • Added focus on loftier goals such as design patterns, frameworks etcetera
  • More entries on learning styles, techniques and tips
  • More complex apps
  • And much more…

So stay tuned and have a great year.


Hoisting in JavaScript

Everyone’s heard the all too familiar, JavaScript is an interpreted language spiel. That’s only partly true. Certain instances  can catch unwary developers out about this idiosyncratic run-time behaviour.

When a JavaScript engine parses a code file, a global execution environment called the execution context is created. This occurs before the file is executed where functions, variables etcetera are ‘hoisted’ into memory. Think of this as instantiation in other languages.

Hoisting is what allows function calls, which occur before the function definition, to run without throwing an error – as the entire function will be hoisted to memory.

This causes issues where function expressions are used. Function expressions are anonymous functions which are assigned to a variable as opposed to a function statement:

// Function Statement
function doSomething(){
   console.log("something done");

// Calling 

// Function Expression
var functionHolder = function() {
   console.log("doing something else");

In this case the variable functionHolder will be hoisted into memory, however it will be ‘undefined’ until the interpreter reaches the actual line where the anonymous function is assigned. At this instance a function object is created and assigned to the variable functionHolder.

For more details about functions expressions, see:
the official description on MDN
JavaScript functions
JavaScript callback functions

JSON and JavaScript Objects

JavaScript Object Notation (JSON) is the lightweight alternative to tag laden XML used as data exchange format. What it is, precisely, is a method of data transmission based on JavaScript’s object literal syntax.

JavaScript objects are containers which store key value pairs of attributes, functions and other objects of the following appearance:

var anObject = {
 firstProperty: 'someString',
 secondProperty: 111,
 aFunc: (parameter) {
         // some code
 isJSON: false

JSON follows the same exact pattern:

  "firstProp": "someString",
  "secondProp": 222,
  "isJSON": true

Few items of note that distinguish between JSON and plain old JavaScript objects:

  • JSON requires that properties by enclosed in quotes, while JS Objects can do it either way.
  • JSON only contains key value pairs, no functions

Back and forth

Although not part of the language, its ubiquity means that JavaScript has helper methods to handle JSON. Most common function is to convert from an object literal to JSON and vice versa:

// Object literal to JSON
var myObject = {
   firstProp: "someString",
   secondProp: 222

var JSONresult = JSON.stringify(myObject); 
// Result
//  {"firstProp": "someString", "secondProp": 222 }

// JSON to Object literal 
// result
// { firstProp: "someString", secondProp: 222 }

So although similar, JS objects and JSON are not the same. In essence JS objects is how you might be normally at home, relaxed and casual versus while JSON is like being in public with more formalised rules.

HTML5 enhancements

Now it’s been some time since HTML5 came on the scene. It’s shiny new glean has been replaced with a well worn veneration and stability.

Although it’s made some marked improvements over its predecessors in terms of not requiring laboured attributes or overly strict syntax, one of its tenets means a certain level of backward compatibility still exists. And owing to the certain habits or strict requirements in the past, some developers simply would’ve stuck to those habits or not realised that with the latest iteration, that some items were no longer needed. This lists the obvious, and not so obvious items.


This is the most obvious one and one which is required. So, without delving into all the iterations and variances, the last two major branches, XHTML and HTML 4 series required a lengthy declaration of the schemas used for the document type defintion (DTD). HTML5 did away with all the cumbersome description and replaced it with the all too popular and well received

 <!DOCTYPE html>

Linking to external files

A CSS style sheet is referenced in an HTML file by using the <link> tag, while JavaScript is referenced via a src attribute in a <script> tag. Where the JavaScript reference required an attribute to specify it was of type ‘text/javascript’, and similarly with CSS being ‘text/css’, is no longer required.

<script src="js/script.js" type="text/javascript"></script>


HTML5 enables asynchronous loading of scripts without locking the other processes from loading in a browser. This is done by using the async tag

<sript src="js/script.js" async></script>

How? By using the async attribute preventing users from having to worry about script link placement and all the consequences the decision imbues.


Defer is similar to the Async attribute, however, it can be used when multiple scripts are needed and should be loaded in order. Scripts with this attribute will wait to execute until the page has finished loading.

These are some of the enhancements for the moment. If there are ones that I have missed, especially major ones, let me know in the comments.

Get started using web API’s – Luas Forecasting API Part Three

After much struggles, see the previous entry for the history up til now, the responseText message was successfully parsed and the information populated on the page:

Luas Arrival Time

Luas Test App

Some of the pitfalls:

  • Response message was a string which wouldn’t yield to any XML extraction methods. That was sorted once parsed to XML. (Response methods for XML didn’t yield anything or issues further along made me dismiss it altogether.
  • It was impossible to extract any data, attempts yielded
    • XML Object Element.
    • HTML Object Element.
    • Null.
  • Xpath was used to get at the data but still no luck (some remnants can be seen as code or comments).
  • API was down for maintenance which didn’t allow much progress.

There were myriad of explanations and convoluted methods to get the data but the issue lay in that the information needed was in the attritbutes and not in the nodes. I’ll do a clearer, indepth write up of all the steps taken to create this but for now this shall be parked.

Some improvements I’m planning on however include:

  • Automatic updating of the page when the response refreshes.
  • Selecting stops by name and whether inbound or outbound.

Stay tuned for that and more!

Get started using web API’s – Luas Forecasting API Part Two

Continuing on from the last post – Get started using web API’s – Luas Forecasting API Part One , there was a slight issue I ran into. This was resolved after several commits where I’d tried to see if I could print out the response regardless of the response status. However those failed and can be seen in my commits [1] [2]

The issue was that I couldn’t get any response message back once the code was hosted on github pages – It worked perfectly on my machine (hey oh). It would just default to the else condition in the httpRequest’s onreadystatechange update – i.e. the assigned function alertContents() would return the message if the response wasn’t in a readyState of ‘DONE’ and status wasn’t 200.

else {
 alert('There was a problem with the request\n');
 alert(httpRequest.responseText); // added an alert to see what message 
                                  // being returned - there was none.

The responseText from the httpRequest didn’t contain any message to help troubleshoot. The problem was later pinned down to a mixed content issue – it’s one where the calling code requests a non secure request ‘http’ and the API would send back or expect a request call to be secure and hence return a secure response.

With that sorted, the next step still remains: Extract information from the xml response and update the webpage. For now here’s the page, click the button to get a raw response message in all its glory.

Get started using web API’s – Luas Forecasting API

My JavaScript excursions have taken a damper as of late. Without much digression, the next mini project I want to tackle is how to consume an api and present it on a page. I’ve been having a bit of internal conflict if I should conduct this on GitHub or codepen and came to the conclusion that i’ll do it on both – first attempt on GitHub and a cloned, improved version, on codepen.

For this tutorial, of sorts, will include the following:

  • Consume the public Luas API
  • Extract relevant information and display on a page

At this point it will only be for a specific location and inbound shuttles. At this stage the HTML & CSS have been setup, as well as the AJAX script to call the Luas Forecasting API.

The API only seemed to show tabular information and not much of explanation or examples are available, bar one on the page for the aforementioned API. It seemed to be only displaying the current status, however, when it was retrieved, the response contained all the relevant information that is needed i.e. the stop name, inbound/outbound and luas arrival times.

Luas Forecasting API response message

Luas Forecasting API response message XML

The next step will be to parse the XML received and push the relevant info to the page. The code so far is available on GitHub. One issue is the GitHub page the AJAX call refuses to play nice. I’l have to look into that as well the next time around, stay tuned!


Javascript functions

JavaScript allows numerous ways in which functions can be created and invoked.

Named functions

These have a name associated with them

function nameOfFuction(){ // code goes here; }

Assigned functions

These are usually named or anonymous functions which are assigned to a variable

var someName = function someFunction() { // code; };
// invoking the function like so

In this case the function is considered a statement so needs to have a semicolon unlike a typical function declaration.

Anonymous functions

These are functions without a name and are most suited for assignment to other variables, in fact the previous function type would be far better using anonymous functions.

var someName = function someFunction() { // code; };
// invoking the function like so

Another way anonymous functions can be used is by having it as the return value of another function

function mainFunction(param1, param2){   // code   return function(){
      // code 

In order to utilise this, the main function itself will NOT work as it will only return the function statement it contains within its body. It is returned in a structure known as a closure:

 // This will return anonymous function from the main function body
mainFunction(paramValue1, paramValue2);
( function() { //code } )

It can, however, be assigned to a variable and thus run like an assigned function

var functionRunner = mainFunction(paramValue1, paramValue2);

or it will need to have a pair of parenthesis added to the end of the function call if it is to be invoked like a standalone function, which will not be returning a function.

mainFunction(paraValue1, paramValue2)();

What is happening is that  the returned anonymous function will get the ‘()’ and be invoked like a regular function call. This is known as immediate function invocation.

A brief intro to Node.js

This is a topic I’ve been meaning to approach for a while now. As it happens, one of my college courses – Web Applications – requires a project built using Node.js, so what better time to tackle this.

I had mentioned Node.js in a previous post, where I was talking about the various environments JavaScript can be run in. This post won’t go into the history or specifics of Node.js; the main exercise will examine the various items found in the sample code for creating a simple Node.js server – which will explore and detail node specific aspects as well as JavaScript patterns used. The code can be found on the About page on the Node.js site:

const http = require('http');

const hostname = '';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);

Play by play

The very first line of code, allows us to import the module ‘http’.

const http = require('http');

This is the implementation method that is specified in CommonJS, which is an ecosystem for JavaScript outside the browser. This is a synchronous system which allows importing of modules or files; since everything will be on the server side. This allows us to import the module http.

The next two lines set the IP address of the localhost (the machine you are currently on) and the port to listen to for incoming requests.

const hostname = '';
const port = 3000;

Immediately following that, the createServer() method is called on the http instance we created on the first line. Which is then assigned to a constant called server.

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');

This is passed a call back function with two parameters and uses an arrow function (read more about it here [1] [2]). This createServer() method will be invoked by an incoming event, in this case web requests. The req parameter will contain all the incoming request’s details. The res parameter will handle the response which will be sent out. In this case it’s setting its statusCode to 200, which signifies that the request was handled successfully. After which the response’s header information is set to indicate it’s content which in this case is plain text. And finally some plain text output is shown while closing the response – this will be displayed in the browser.

The final section of the code, referencing the server which points to the http.createServer() call, is set to listen on the port and host IP address set above.

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);

The arrow function will display the message indicated while the server is running in the node.js environment giving us a visual that things are working.

There you go, this was just a quick run down to help try and elucidate, both for me and anyone reading this, what is happening within this simple node.js server code. Stay tuned for more practical topics on the matter.