JavaScript binary to decimal application (Part Three): The Flux Capa… Convertor

Ok been on a hiatus due to work/college and most importantly my first born. So after a much waited delay, here’s the final piece – the actual conversion from Binary to Decimal.

This is the logic, which I took adapted from my Java lectures.

var convertToDecimal = function(binVal){
  var result = 0;
  var n = binVal.length - 1;
  for (i = 0; i < binVal.length; i++){
    var digit = binVal.charAt(i);
    result = result + (digit * Math.pow(2, n));
  return result;

This takes over from the last check, where we verified if an input was binary, and traverses the length of that input from left to right. Simultaneously var n is set to the positional power of the digit iterated over and added to the digit. The end result of all such additions is the decimal value.

Niggles encountered

I initially set the for loop check as n + 1; I erroneously assumed that since n was length minus one that would make up for the discrepancy, however each iteration would affect the value of n with the decrement (n–) and then the check would add 1 to it. I haven’t checked the full ramification of such a value but it did throw off conversion.

Another snag was that I was trying to set the output field’s value inside a conditional branch i.e.

if (value does not contain 1 or 0){  
  document.getElementById("output").value = input;
} else {
  /* code to execute if input is binary */

This was before, when I was doing a test to see output of invalid characters; input is the parameter passed to the function which contains the above conditional. That didn’t actually set the output as I’d expected. It somewhat makes sense when the function call is made – it is set to pass a value back, which expects a returned value.

document.getElementById("output").value = checkInput(binInput);

The line above can be taken to mean it would set it directly but wasn’t doing anything.

Closing Thoughts

So that pretty much wraps up the project in terms of the functionality and what was set out initially :

  • 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.
    • logic for the binary to decimal conversion.
    • restricting the entry value to 1’s and 0’s, probably using regular expression.

Further enhancements might be conducted to improve the user interface. One thing that came up during the exercise is that CodePen isn’t ideal for showing the various stages of the project. So each blog entry detailing the steps I’d taken will all point to the end result and not what it was like at that moment in time. Suppose that’s another issue to contend with if items are being created on CodePen. For the moment here is the completed, albeit unpolished, piece:

See the Pen
Binary to Decimal Conversion
by Donal D’silva (@donyd)
on CodePen.

JavaScript binary to decimal application (Part Two): Regular Expressions

Continuing on from the previous post, where I set up a pen on to create a simple application that would take a binary number and covert to decimal. I’d laid out front end and the two tasks I had left were:

  • logic for the binary to decimal conversion.
  • restricting the entry value to 1’s and 0’s, probably using regular expression.

Filtering binary values using Regex

The one currently on my to do list is limit only binary values being entered into the input field. First hurdle was being able to compare the value input. Regex was my go to choice and was simple enough:

/[10]/g  -- pretty much translates to a range of digits from 1 to 0

However, there were a range of issues:

  • I assumed that even though the expression would find all instances of the pattern, it wasn’t working properly and I would have to create code to iterate through each character in the input [turned out I was using the wrong regex object methods i.e. match instead of test]
  • After finding the right method call ‘regex.test()’ the condition was picking some input which wasn’t binary.

My condition was

if (value contains 1 or 0) {
     /* code to execute if input is binary */
} else {
    /* code to execute if input isn't binary */

Any values which contained either a ‘1’ or ‘0’ would be accurately considered as binary figures. However, the issue was when a non valid input contained either of the valid elements ‘1’ or ‘0’ e.g. 10A, that would be considered binary as well.

I’d searched for numerous forums tips on pattern matching what was needed and excluding others i.e. show me only cases where it’s 1’s and 0’s and excluded everything else. Pretty sure there are ways but none that I could find.


The solution was very simple however, by seeking a pattern that considered everything except 1’s and 0’s and then using that as the filter to discount all non valid binary  input meant that the remaining items would surely be binary values.

if (value does not contain 1 or 0){  
  /* code to execute if not binary */
} else {
  /* code to execute if input is binary */

See the Pen xELLJP by Donal D’silva (@donyd) on CodePen.

Closing thoughts

The task was deceptively simple, even though it proved somewhat daunting in the beginning. Further excursions into Regex is warranted, just to get beyond the basic pattern matching that can be done. So with that we’re one step closer to the end goal.

JavaScript binary to decimal application (Part One): Getting Started

Following on the heels of the last blog “Enter your destiny here – Javascript binary to decimal“, this entry will pickup and start on the tasks for creating what was set out – creating a web application, of sorts, to convert a binary entry to decimal representation.

Firstly, a place to develop and host it. is my go to choice. Now this is almost ad-hoc and not planned out or scoped (I guess more software engineering principles will be focused later down the line).

First Steps

  1. The first stab involved setting up an HTML front end with a minimal of styling with CSS. It consists of two input boxes and a button.
  2. Then I changed the text styling from something other than default.
  3. I experimented with getting and setting the text boxes values with JavaScript.
  4. Then once those were working I putting them into a function.
  5. This function was then called on the onclick property of the button.

So this basically allows text to be entered into one input box and clicking on the button will push it to the other one.

See the Pen
Binary to Decimal Conversion
by Donal D’silva (@donyd)
on CodePen.

It’s nowhere near completion but not too shabby for rabid typing in between a lecture (Java of all classes).  So this will be the first iteration and more soon to follow, including:

  • logic for the binary to decimal conversion.
  • restricting the entry value to 1’s and 0’s, probably using regular expression.

Closing thoughts and caveats

One constant internal nag that I had was that the html elements weren’t entirely up to standards. I just essentially cobbled together items from memory and out of necessity i.e. I need a text box, just get it in and enter a non semantic, untagged text as its label.

Also I initially had an issue with the JavaScript (I’ve not had the best of experiences wiring up JavaScript with HTML contained in a browser before). Especially with event handlers, of which, I’m assuming, the onclick is one (see shows how much I don’t know). Which lead me to believe that I’d done it again. However, the issue was that I was trying to push the value of an input box into an HTML element.

I’d created an empty paragraph <p></p> to which I added an Id and then tried to push the value into that empty paragraph. It’s only later that I realised that I would’ve had need to affect the innerHTML property for an element like paragraph. It works fine with the input fields, as it does have a value property that can be updated with an getElementById train.


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

Scope in JavaScript

JavaScript implicitly types variables, i.e. you don’t have to do it yourself. Similarly there’s no access modifiers used, bar one. This ‘access modifier’ – the var keyword – isn’t intuitive in the least.

Check out the video I made on the topic

Does it imply that something is a variable? And the fact that variables can be created without it leaves people thinking its usage is stylistic. However var’s purpose is very different and unlike languages that are strongly typed or Python which actually uses an intuitive keyword in its stead – global – var is somewhat ambiguous if used at all.

Its function is to somewhat identify whether a given variable is local or global in scope. To further add to the confusion, anything that is declared in a JavaScript file will be considered global in scope, outside of functions and closures that is.

Function variables

Variables within a function are scoped to that function only. This includes parameters. For the sake of this explanation let’s just focus on variables within function bodies.

var a = "outside function scope";
var b = "still outside function scope";

function showMsg(){
    var a = "inside function scope";

showMsg();  // displays -> "still outside of function scope" 
alert(a);   // displays -> " "outside function scope"

in the preceding example, the alert method will show the value of the global var a which is declared at the top of the code. The var a delcaration within the function ‘showMsg()’ is not accessible outside the function.

By changing the scope of variable ‘a’ within the function by removing the keyword ‘var’ however, its scope is changed to global and this will overwrite the variable a in the global scope. The alert(a) call will return with the assignment inside the function call, namely the message, “inside function scope.”

function showMsg(){
    a = "inside function scope";

This may appear that it’s referring to the variable within the function, however that scope ceases to exist once the function call returns.

UPDATE (25th Feb 2018): Just wanted to point out that this writeup is slightly misleading. In this instance removing the keyword var from within the function showMsg() means that it is merely referring to the variable ‘a’ which we declared in the global scope i.e. var a on the first line.

If however, we do not declare it outside and instead declared it only inside the function without using the var keyword, that variable will be available globally. However, the variable contained within the function will not exist in the execution context until the function has been invoked at least once.

JavaScript Consoles

The one bane of JavaScript development is that it’s not as easy to run  code as instantly as a compiled language such as C# or Java. Even when using a fully featured IDE, the results are limited to attaching it to a browser port via HTML to see the results. There are some options however. Some require internet access, others once set up, such as Node.js, allow you to execute the code with nothing more than the CLI.

Browser Console

The ever present and common tool that most web development enthusiasts would be accustomed to is the built in console that most modern browsers have. This is usually a part of a comprehensive set of developer tools that most browsers come bundled with. It’s a simple as opening up the console and typing in JavaScript commands. Each browser has it’s own implementation but the base level items should be quite similar to someone familiar with one.

Firefox browser console

Firefox browser console running JavaScript


CodePen has been a stomping ground for front end wizardry or as a platform for experimenting and seeking feedback. So with this new JS console, not only can HTML/CSS/JavaScript and various extensions thereof be shared, but also the code output. Read the official update on blog.



Another similar code sharing site is JSbin, in fact the JavaScript console  for Codepen is an almost complete port of the one used in JSbin. JavaScript entered in the JavaScript section can be seen either in the output section by virtue of it’s effects or the results directly seen in the console by logging items to it. Find out more about JSbin here.




Enter server side JavaScript. Apart from that Node.js opens up JavaScript on the development machine itself, allowing access to native file system, create utility scripts etcetera. One of the cool thing is the ability to run a Node.js command prompt which allows the running of snippets of code typed directly into the prompt or running script files.




Now this is a interesting concept from Adobe. It’s a lightweight code editor with JSLint baked in and one very invaluable feature is the ability to attach to a running browser process and see updates made to either the HTML/CSS/JavaScript in the browser’s viewport instantly. At the moment the only supported browser is chrome and is expected to expand to others. text editor

Brackets text editor


Dynamics CRM – Access GUID from the browser console

Now this blog hasn’t quite morphed from its primordial form and I have yet to declare its mission statement.

In a nutshell it is to log and explore all aspects of my  journey through learning JavaScript – its many utilities and facets. One such area is its use in Microsoft Dynamics CRM.

So without discussing further details of background of JavaScript use in CRM, I’d like to rehash a quick and easy way to retrieve a form’s GUID (Globally Unique Identifier) through the browser console. Just to point out that this tip comes from other sources [1] [2] but I noticed it wasn’t quite working.

The posts suggests entering the following into the browser console:


However doing so in Firefox throws an error saying that data node is null.


The issue is that the first index of frames i.e. frames[0] is actually referring to the list of records from the current view and not the actual record instance itself.

Typing in frames[0] in the console illustrates this:


This returns _root branch before the page itself. Clicking on this should display the list of records. The implementation seems to have undergone changes since CRM 2013.

In order to access the record directly and therefore its GUID the correct frame index is 1:


Clicking on the link returned will open the record in a new page. So with this index change the call mentioned in the original blog(s) will return the record’s GUID.


Note: I haven’t tried it on IE or Chrome as IE keeps crashing constantly when the developer tools is opened. and I just haven’t bothered with Chrome.

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.

JavaScript Arrays – Push it real good

A quick shout to JavaScript array methods. With ECMA-262 version 5 (latest version 6), came several new methods for manipulating arrays. Lets focus on the ones that allow user to add or remove from either end of an array.

Add an item to the end of an array: push()

The push() method allows an element to be appended to the end of an existing array.

var someArray = ["itemOne", "itemTwo", "itemThree"]; 


someArray;  // someArray now contains["itemOne", "itemTwo", "itemThree", "itemFour"];

Remove an item from the end of an array: pop()

The pop() method removes the last element from an array. It also returns that removed element.

var lastItem = someArray.pop();

lastItem; // contains "itemFour";

Add an item to the beginning of an array: unshift()

The unshift() method adds an item to the front of an array

someArray ; // now contains ["itemZero", "itemOne", "itemTwo", "itemThree"]

Remove an item from the beginning of an array: shift()

The shift() method removes and returns an item from the front of an array

var firstItem = someArray.shift();

firstItem; // contains "itemZero"

JavaScript, a brief history

Hindsight, they say, is 20/20. But being the emotive beings we are, origin stories tend to have an aura of nostalgic romance, even if it be vicariously.

The tale of JavaScript is no exception. From its creation,  the many a mired versions of how it came to be called what it is today, and to the period of hiatus leading to the eventual renaissance, is more than enough to lay ground for a mythical lore.

An Idea is born

The first prototype of JavaScript is said to have been drafted by Brendan Eich. Eich was given just ten days, by Netscape to create a new scripting language for its browser.

Mounting contention with preexisting scripting languages made the notion of a new language tenuous at best, especially when it didn’t even exist. Varying sources list that JavaScript was either based on and/or vying for supremacy amongst other languages – namely “AWK, Java, Perl, Scheme, HyperTalk, and Self” [1][2]. Furthermore, this discussion also eschewed the merit of another language when Java, a fully featured language, already existed.

I dub thee JavaScript

JavaScript was initially code named Mocha by Netscape and then later LiveScript. The now ubiquitous moniker purportedly came about while Netscape was in talks with Sun Microsystems about including Java in their Navigator web browser.

Sources differ about how or why the name came about, but the only unequivocal aspect is that culmination of all deciding factors and entities resulted in LiveScript being renamed JavaScript in late 1995. Whether this was based on riding the popularity of Java or a press release misinterpreted by the media and early target audience will most likely be always up for debate.

Why no love?

The bane of why JavaScript has had its detractors from almost the very first instance to the present is part reason why a disparate language was justified by the pro crowd within Netscape. JavaScript had to have been simple in terms of learning curve and utility i.e. it was meant to be a lightweight and forgiving language that could be used by novices or web designers to assemble the components provided by the more powerful Java counterpart or automate interactions [2] [3]. Java already played the role of the heavy hitting, yet siloed, powerhouse; JavaScript was meant to be based on Java but never compete with it and therefore was a stripped down affair, albeit being a “rich and powerful language” minus the object oriented paradigm [4]. It would be simple enough for novices, yet powerful enough for those skilled enough to use it.

Even though JavaScript was a powerful language, being targeted at novice users, and a slew of other teething issues relegated the language to being ‘simple’ and for the uninitiated by professional programmers [3]. This loathing exists even to the day for mostly the same reasons .

In spite of the tribulations and somewhat windy tenure, JavaScript has endured and is most definitely a key language not to be ignored.


[1]Jones, D. (2014) JavaScript: Novice to Ninja. Victoria: SitePoint.

[2] Rauschmayer, A. (2014) Speaking JavaScript – An In-Depth Guide for Programmers. Sebastopol: O’Reilly.

[3] Champeon, S. (2001) JavaScript: How Did We Get Here? O’Reilly Web DevCenter. Available at [Accessed 26 Mar 2016]

[4] Severance, C. (2012) JavaScript: Designing a Language in 10 Days. IEEE Computer Society, 45 (2) pp. 7-8. Available at