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 
functionHolder();

// 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 
///////////////////////////////
JSON.parse(JSONResult);
// 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.

DOCTYPE

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>

Async

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

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:

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!