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

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

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 
   };}d

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

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.

JavaScript: Asynchronous Programming Primer

Some aspects of JavaScript are well known, or well loathed, mostly because it’s only partially understood. Some of these include that JavaScript is an interpreted language, which is not entirely true, which we’ll save for another day. Another is that JavaScript is a single threaded language, which is true but there are structures which allow more than a single thread to operate.

A city called asynchroni… city

Asynchronous programming allows multi-threading via Web API’s (such as event handlers) that handles processes and return tasks to the browser separately from the main thread.

The cycle follows that when a function or other code is encountered, it is placed on the Call Stack and the stack at this point is unavailable till this code is executed. The Call Stack is the data structure that handles function calls in the order that they were executed, i.e. first in, last out. This stack is the main thread that JavaScript runs on in browser. If, however, an asynchronous function is encountered, the code is deferred to a non Call Stack process to handle,

These other processes run the code, which are sent to it as callback functions, whose results are then queued in the Event Queue. This is eventually passed back to the Call Stack when it is empty. A common Web API that processes such asynchronous calls are Timers, these include:

setTimeout()

The setTimeout() method can be used to put a task on the event queue.  The method takes a callback function as the first argument and the amount of time to wait as the second argument. The time value is numeric in milliseconds. e.g. 500, 1000 which equates to half and one full second,

setInterval()

This is similar to the setTimetout() method however, the call back function will be called non-stop after each time value period lapses.

Stopping Timers

Each method above can be stopped using the related stopping methods:

  • clearTimeout()  // for setTimeout()
  • clearInterval()   // for setInterval()

When the respective timer events are created, it returns a numeric id which can be stored in a variable and then passed on to the methods indicated. This allows targeting a specific timer instance to be stopped.

Conclusion

Asynchronous programming allows processes, which would otherwise tie up the browser and make it unusable to another handler and return the results to the main thread. Thus allowing the application question to be efficient and responsive.

This is just a small primer on the asynchronous capabilities of JavaScript on the browser side. Stay tuned as more write ups will focus on this topic and related areas.

Enter your destiny here – Javascript binary to decimal

The bane of learning programming, it seems, is mostly waning effort or focus. This might not be due to lack of interest, but personally, like lots of effort spread over many different things, or specifically, to one particular item, none of which seem to gain any traction.

You just seem to go through the motions of learning the syntax or solving mini tasks or challenges online, or almost mechanically going through tutorials without ever seeming to gain a viable grasp, let alone mastery, to be able to generate code without looking up examples or asking others.

The only time something seemed to stick is when you are attempting to solve a problem or challenge for yourself. This seems to embed the knowledge/skills more deeply and doesn’t leave you feeling like you’ve just written across water. A beneficial side affect is that your focus has narrowed to a point where you might only require a select range of knowledge and skills, instead of a consuming an entire book or 5+ hour tutorial.

So with that in mind, the only efficient means of learning, I can see of being of any value is to start my own projects or try and create things or solve problems with code. The first item I plan on tackling is:

  1. Creating a HTML/CSS/Javascript implementation of a problem we had to solve in a Java class – given a binary value, convert it to its decimal counterpart.

Now this should be fairly simple as the logic was somewhat nailed out and then later given to us, so it’ll be merely a way of translating that into a web based application.

Update: here is the first in the series of entries that catalogs that –
JavaScript binary to decimal application – Part I

Accessing JavaScript object properties indirectly

When it comes to accessing data in JavaScript objects there are two methods available

  • dot operator .
  • bracket notation []

Take as a example an object with the following properties:

var newObj = {
  propertyOne: "some string",
  propertyTwo: 2,
 "property Three" : "other string",
  4 : "Four"
};

Dot Operator

The dot operator is typical to method call chaining or tree style traversal.  It is useful when the name of the property is known.

newObj.propertyOne;   //  some string

Bracket Notation

The bracket notation is similar to the dot operator in the chaining process i.e. the object followed by property name.

object[propertyName][otherProperty]; // so on.

It is useful if the property name has a space in it (“property Three” for instance). But a more beneficial use is when the property’s name would vary, such as when iterating through a list.

 The bracket notation allows the use of variables as placeholders for a property’s name.

A simple example :

var placeHolder = "property Three";
newObj[placeHolder]; // yields "other string"

This is typical in a scenario  where a function is required to access or update an object’s properties. In building the function, the parameters would be generic and the dot operator would expect the exact name of a property to work. So a function signature with generic parameter names wouldn’t work:

function getProperties(ObjName, propName){
 var result = "The item you looked up is" +     ObjName.propName; 
 return result;
}

This simple example defeats the purpose of a lookup requiring only those two parameters itself, but the point is that using generic parameters means that this can be used in numerous contexts.

The dot operator used would result in undefined as the method would be looking for the specific property name.

The bracket notation, on the other hand, allows the use of variables containing the value of the property name assigned to it:

var placeholderName = propertyOne;var placeholderName = 1;

So this works well with parameter variables which would act as placeholders for a functions input.