JavaScript String Interpolation

Up till now in JavaScript, the only way to ever insert variable content into a string was to concatenate the string with the variable, ensuring that there was proper blank spaces around the text to ensure that it looked like a normal sentence :

var name = "Simon"; 
var age = 24;
var sentence = "Hi, my name is " + name + " and my age is " + age;

Other languages such as ruby, C# have had a handy little feature that allows placeholders to be used inside a string literal i.e. anything between the single or double quotes. This alleviated the long winded string + variable + string… formations.

ES6 (EcmaScript 6) brings this capability to JavaScript with String Interpolation. In similar fashion to languages that have had this feature already, it works by using template literals as placeholders within the quoted text:

var name = "John";
var age = "30";
var sentence = `Hi, my name is ${name} and my age is ${age}`;

Apart from the Template Literal – ${variable} – token, the other thing to take note is that back ticks “ are needed and not the usual single (‘ ‘) or double quotes (” “).

ScrollMagic – Pinning Tutorial

So I didn’t quite start on what I had previously said I would – rebuliding one of my first apps ‘Luas App‘ using React.js. Instead I got sidetracked by my many a feathered, tutorial hell and tumult of life. I did however been meandering through various endeavours in the social media space focused on coding. First being my latent programming youtube channel

And the other being my new instagram page (channel, space?):

So in the midst of all that, I came across yearly periodical “The Ultimate JavaScript Manual 2019.”

Some interesting reads, good for getting to see what’s what from the who’s who on web development – I think. Apart from the tooling section, the frameworks and examples aren’t my cup of tea. You still fall into the tutorial trap.

One that I picked was Scrolling animations using ScrollMagic. Looking back at the article, I HIGHLY doubt I did the tutorial mentioned. Instead I just made a quick tutorial video while I was trying to pick apart the items they had mentioned and trying it out on my own.

These are the key points:

  • ScrollMagic works on the concept of controllers and scenes.
  • Controllers set the stage for the animation objects and global settings of any contained scenes.
  • Scenes define the settings for the item being referenced e.g. a floating indicator, or navigation bar that needs to be pinned to the viewport.
  • Once the scene is set, it is passed onto the controller to take effect.

I only used jQuery and the ScrollMagic library and plugins – the latter two is shown when you first visit the ScrollMagic site.

For the setup and walkthrough, check out my video tutorial:

I’m hoping to get back into ScrollMagic animations soon and do some more explorations and tutorials. So stay tuned. Until then, adios.

Site is back up!

It’s only been a month, and few days since the last post. In a bit to prevent spam comments on the site I installed akismet. However that resulted in the site breaking and me left with a 500 server error with not a clue what the hey was going on.

Brown rolled hay

After finally fixing the issue and being able to access the site, the spam comments seemed to be getting worse – roughly 2-3 almost every 5 minutes. So had to re-break the site and leave it hanging with a 500 error.

Fast forward to today, finally got the site back online, spam control installed and functional AND also got the child theme back up :D.

First order of business is light clean up of posts and refresh images and links. Other tasks to follow:

  • Update change log
  • Extend child theme
  • Build extra sites to focus on non javascript topics

That’s it for now. Stay tuned.

New Year, New Host!

Betwixt the many moorings of life’s business, JavaScript Unscripted has moved hosts – now both and are under the same registrar – NameCheap.

I just managed to import all posts from the previous wordpress blog and nearly had a conniption, as subdued as my demeanor allows. Yes, quite. So between reinvigorating this blog and other much needed maintenance – key being bringing my custom theme back – stay tuned!

JavaScript: remove leading and trailing spaces

Ramble Preamble

Hot on the heels of finishing off one of my non-JavaScript mini projects – the reason why there’s a lull of late on this blog – I’d come to the weary conclusion that somethings you just need JavaScript for. The project in question is a web port of a simple csv convertor desktop app built with python and tkinter.

The web version was done using flask – a python based micro web framework. Most of the logic required was done with the desktop version, which was just simply transferred to the server side code and worked without a hitch. The snag was that the user input had to be sent via a HTTP POST message that would be picked up by the flask routing system, processed and then sent back, not ideal in of itself but stuck with it as I couldn’t find any alternative. The problem was that the post message had a size limit and thereby dropped anything over 1567 rows…

…what can be done in the browser should be done in the browser.

Enter the JavaScript

Realisation slowly dawned that JavaScript is needed, as what can be done in the browser should be done in the browser. Everything was fine until I found out that JavaScript was limited in terms of being able to trim leading or trailing spaces, or so I thought.

A quick search of something similar to Python’s lstrip or rstrip brings up several articles which talk about either using the trim() function introduced with ES5 (ECMAScript 5), extending it using the prototype chain or, prior to that, just crafting your own function using regex expressions.

It just so happens that there are native functions built in that accomplish what I need –

String.trimStart() – Remove trailing spaces from the start

String.trimEnd() – Remove trailing spaces from the end

It’s great for removing any and all trailing white space, including new lines which was causing  trouble with my output. However, unlike their counterparts in Python, these functions do not allow passing any character inputs as filters. For e.g. in python, specific characters such as trailing commas or formatting tags like carriage returns or new lines can be passed for removal

Convert to CSV

In my case my code would append a space followed by a comma ” ,” to the end of each row input. This presents a trailing comma which the Python rstrip would take care of in one swoop, of the fell kind. However, thanks to finding the trimEnd() method, the solution that presents itself is very simple if not crude. Come of think of it, I could have easily solved the problem of trailing space with just the trim() function. Anyway here’s the sols:

After having to troubleshoot why my slice wasn’t working as it should – there was still trailing white space – I came to the sobering relisation that the split function does in fact split everything into a new comma separated list (doh). Anyway the extra formatting on line 10, as it was renamed to later on, does exactly that now, but wasn’t needed. Ah well, hindsight is 1 they say…which is what I calculated 20/20 to be – true.

So here’s to polishing off this project with just the bare minimum functionality for the moment, which is convert to CSV.

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() { // 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){   
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.

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:


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,


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.


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.