Javascript Recursion, Variable Scope and Hoisting

One of my most popular posts involved javascript function declarations vs function expressions. On the post, I mentioned something but never went into detail how it works properly. In this post, I’ll try to address it by using an example I encountered recently.

While going through an online javascript quiz, I couldn’t figure out why my code wasn’t passing. The task was returning the sum of all integers when given an array. The array could contain any data, including other arrays. By any means, my solution should have been returning the correct result but it still wasn’t responding the correct way. I had to do some line by line debugging and considering it was a recursion function, things can get tricky. At the end, I was certain the recursion function was the culprit.

My initial solution looked like this:

function arraySum(i) {
 sum = 0;
 for(var x = 0; x<i.length;x++){
  if(typeof i[x] == 'number'){
   sum += i[x];
  }
  else if(i[x] instanceof Array){
   arraySum(i[x]);
  }
 }
 return sum;
}

This one obviously failed and would return the sum of the innermost array. If you tried to run arraySum([1, 2, 3, [4, 5]]), it would return 9 instead of 15. This is seemed obvious due to the return line operating in the recursion function breaking off.

The next solution was the trickiest one to figure what was going wrong:

function arraySum(i) {
 var sum = 0;
 for(var x = 0; x<i.length;x++){
   if(typeof i[x] == 'number'){
   sum += i[x];
  }
  else if(i[x] instanceof Array){
   arraySum(i[x]);
  }
 }
 return sum;
}

This function would only return the sum of the outermost numbers and never include the sum of the inner arrays. If it isn’t obvious yet (it wasn’t obvious to me for about 30 minutes), variable scope was at play. In the original function, due to the order of the conditionals, it would return the correct result if, and only if, the array passed had the innermost array as the first element. If you had 3 or more nested arrays, then the deepest array should always be the first element of the parent array. If you passed arraySum([[4, 5], 1, 2, 3]) in the initial function, it would return 15 which happens to be the expected result.

In the second solution, only the sum of the outermost array would be returned. Both arraySum([1, 2, 3, [4, 5]]) and arraySum([[4, 5], 1, 2, 3]) would return 6. This ruled out the order of the elements and highlighted the variable scope complications present.

Variable scope refers to the extent of the availability of a variable in code. In javascript, variable scope is prominently present in functions. If you declare a variable using var x in some function y(), x will only be available inside the y().

Applying this logic in the second function, it becomes obvious why only the sum of the outermost numbers were the only ones returned. Precisely, refer to the second line in the second function (i.e. var sum = 0). Every recursion function had its own scope of the sum variable. Hence every returned sum value by the inner functions wasn’t available to the outermost function

Taking this into consideration, the final solution looked like this:


function arraySum(i) {
 var sum = 0;
 function sumArr(i){
  for(var x = 0; x<i.length;x++){
   if(typeof i[x] == 'number'){
    sum += i[x];
   }
   else if(i[x] instanceof Array){
    sumArr(i[x]);
   }
  }
 }
 sumArr(i);
 return sum;
}

To avoid the variable scope issues, I opted to employ a closure. It ensured neither the order nor the scope was going to change the final returned value. There are other impressive hacks that avoid using recursion altogether but I opted using a closure to illustrate the problems one might run into when faced with recursion functions.

On a funny somewhat unrelated note, try this in your browser console:


var definitelyNotANumber;
definitelyNotANumber += 2; //NaN
typeof definitelyNotANumber; //wat?

Guess the Number Game

A few months back, I managed to create a second draft of a popular number guessing game. My first draft was an elementary attempt, and one of the first JavaScript code I wrote. It was for proving I could write JavaScript code and its execution flow. I revisited the exercise and decided to use jQuery and create something more interactive and fun.

The exercise employs Binary Search Algorithm. It is one of my favourite algorithms due to its simple and logical approach. It is very useful for getting people to think in terms of binary.

The second draft can be visited here. In the third draft I’m planning on using MV* structure, in particular Backbone.js.

Creating a GIF using HTML5’s Canvas

Lately, I’ve been envious of what other people have created using Canvas. It seems like HTML5 is becoming synonymous with Canvas among certain designer/developer groups and everyone seems to be doing amazing things with it. I decided to go the opposite way and solve a problem that doesn’t exist in the first place. A GIF-style animation with playback controls. So, essentially a muted video. I have gone the full circle.

I got this idea after realizing you can actually plot an image using Canvas built-in functions. The particular canvas function in this case is the .drawImage(src.jpg,height, width). From there we can easily see how this unfolds. Not really? Well, hop on the train to Hipsterdesignsville.

First of all, you need to find a gif frame-splitter. This could be any tool, from your photo editing software to any one of the multiple online tools. In my case, I used GIF Explode as I was only using an 8-frame animation. I highly recommend it. The idea behind this exercise is as follows: i) arrange a number of frames in their respective order ii) make a function that obtains an image and displays it on the canvas iii) finally make this function iterate the array of images using setInterval().

I also added a few fancy buttons for control of the animation. Basically it gives the ability to pause, play or rewind. This is the part where I feel canvas gets a leg over gifs.

You can see the full animation in action here.

 

GMail Scripts: Putting an automatic label on new e-mails

The last couple of posts have been tech related due to heavy work and/or lack in activity on other interesting topics I like to yap about. Football season is over and summer seems to be finally setting in (although the current weather has it’s own ideas) . Anyway, I’ve been going over some JavaScript ideas and I ran over regular expression the other day. I thought it might be a good idea to incorporate regular expression into something a bit more useful.

A couple of months back, while I was learning JavaScript apps, I came upon Google scripts. It seemed powerful and useful but my limited JavaScript knowledge didn’t allow me to do anything useful with it. A month or so later, I found out that I was getting lots of emails that are work related and didn’t want to miss/delete any by mistake. Thankfully, GMail offers ‘labels’ which is just a simple way of marking your emails so you can easily differentiate them. I, manually, labelled my work emails for a couple of days until I realized how pointless it was. If I can mark them manually, then it becomes meaningless to use labels in the first place. And if I miss any, it would be even harder to notice the mistake. Then I remembered Google script and wondered if I could use it to automatically label all incoming emails.

For some background, Google script (actual name: Google Apps Script) is based on JavaScript and as a result, it is very easy to learn. It employs most syntax used in JavaScript, although there are differences to keep in mind. It’s very useful in doing personal projects and I would recommend it to anyone currently learning JavaScript. A huge benefit of using this is knowing that you can schedule your scripts to run at specific times due to being hosted on Google Drive. My script runs once every hour but that can be changed to even once every minute.

I usually receive my work emails from a web-app ticketing system. This usually leads to the emails subject having specific keywords that are common in every work-related email. Hence, I can easily employ Regular Expressions to search for these keywords and apply labels to any new email that contains them. As long as the keywords are unique for work-related emails and all work-emails contain them, I won’t risk losing any mis-labelled emails. The script can be found here. You might need to be logged into google to view it. You’ll also need to set up a ‘script trigger’ which is essentially a way of allowing google to know when and how often to run the script.

I pasted the script below, in case it isn’t visible from the above link:

var label = GmailApp.getUserLabelByName(“MY LABEL NAME”); //getting a label name you’ve specified
var firstThread = new Array(); //An Array that will contain your emails
var matching = /keyword/g; //the keyword you’ll be searching
function lab (){
 for (var i = 0; i<20; i++){ //you can set whatever number depending on the volume of emails you receive on average
  firstThread.push(GmailApp.getInboxThreads(0,50)[i]); //getting all the inbox messages
  var testing = firstThread[i].getFirstMessageSubject().match(matching); //checking whether the 'keyword' in the subject
   if (testing == "keyword"){ //checks whether testing returns match
   label.addToThread(GmailApp.getInboxThreads(0,50)[i])//adds the label to the message thread
   testing = null; //emptying testing before searching the next mail
  }
 }
}

//Couple of useful things to point out:
//- I search for threads because it's easier to look for keywords and label the whole thread instead of labelling individual emails
//- Ensure that the keywords are unique enough to not label emails that aren't related

Javascript Function Declaration vs Function expressions

Anyone familiar with javascript will know function objects are one of the most important parts, if not the most important reference type. Hence it comes with great confusion when they learn that functions can be expressed in various ways. From object elements to stand-alone variables, functions are usually flexible and can be appended to unlimited scenarios.

There are two main ways, however, in which we write javascript functions. There is the function declaration:

function myFunction(argument){
  return argument;
}

And there is the function expression:

var myFunction = function(argument){
  return argument;
}

The question on which style is preferred relies solely on preference of the user. Generally, both ways are acceptable and mostly interchangeable. Majority of people tend to use both without a preferred standard. Chances are when using one, the other can be substituted with no observable differences. There is however a minor but very crucial difference between the two. Consider a function that takes two arguments and returns their product. Below are both methods that can be used to call the function:

FUNCTION EXPRESSION:
var iMultiply = function(x , y){
  return x * y;
}
 
FUNCTION DECLARATION:
function iMultiply(x , y){
  return x * y;
}

Let’s call a variable product that passes the arguments 10 and 20 in the iMultiply function. To point out the difference, let’s call product before we define our iMultiply function

FUNCTION EXPRESSION:
var product = iMultiply(10,20);
var iMultiply = function(x , y){
  return x * y;
}
 
FUNCTION DECLARATION:
var product = iMultiply(10,20);
function iMultiply(x , y){
  return x * y;
}

In the first instance (i.e. function expression), an error will be returned. In the function declaration example, our code will still work. While javascript usually executes code on a line by line basis, functions are handled slightly differently. Before the code starts to execute, functions are usually pulled to the execution context, a process called function declaration hoisting. Function declarations make the respective functions available for execution regardless of their position. Function expression, on the other hand, limits the scope of the function until the line has been executed. This means the function is useless when called before function has been declared.

Aside from this ‘small’ difference, function declarations and function expressions are pretty much identical and can be interchanged.

Notepad++ and NppFTP plugin issues

Notepad++ has been glitch-y when using the NppFTP plugin. I’ve been using it to access servers and it’s a handy tool when employing live updates. The troubles start when I connect using an explicit FTP access (FTPES). Here’s how the access setup looks like (it’s in Vista because life’s a bit sweeter when you live on the edge)

And here’s an early warning on the future problems you’ll encounter.

You should click OK and move on to accessing the server. There shouldn’t be any issues regarding this process. Troubles start when you exit Notepad++ and restart it. You encounter this error.

Notepad++ should be working without an issue. However, when you try and start the NppFTP plugin, you’ll notice that it’s unresponsive. No amount of cursing will work at this point, I should note from experience. The problem however seems to stem from the previous error concerning the certificate. After a few Google searches (and a handful of dodgy websites) I figured out this issue has been common since 2010. Slightly surprising considering Notepad++ is used by a handful of people for such a problem to last this long. In a true IT support spirit I found a temporary solution. Head over to the folder below and delete the “Certificates.XML” file.

Restart Notepad++ and it will prompt you with the certificate’s Y/N agreement when you try accessing your server. Rinse and repeat until the Notepad++ Gods are appeased.

Good news everyone, Notepad++ have fixed this issue.

The Problem with Web Design and Development for most Beginners

I am experiencing a love/hate relationship with web-development. Around 5 years ago, I designed my first website. Mind you, it wasn’t my idea but I ended up doing it after my Maths teacher, and mentor, asked me to help design one for an NGO. He was teaching a web-design club which I immediately joined. I still remember my first tag which involved the ever welcomed “Hello World!”. Like any new hobby, it was wonderful and exciting at first. You learn about div’s, b‘s, i‘s (this was before strong and em) and it all seems rather, for a lack of a better term, obvious. If there ever was a constant in life, it is humanity underestimation of problems (maybe it’s Hofstadter’s Law in motion). After a week or so of html, I thought I had the hang of it. And then I encountered my first big problem, $php.

There are two ways of looking for a solution and one’s approach can easily be used to deduce the relationship between one’s self and the task. First, one could go on a research binge which might include consulting, reading, observing other solutions etc. This usually implies one is willing to learn from the challenge and hopefully solve future similar problems. The second, and my less favourable approach, involves throwing the task to someone else. Unsurprisingly, the solution cycle usually involves a parts of both approaches. However, the best approach is try to stick with the former than the latter. When I first worked with php, I never wanted to try the first approach. If I ever have to introduce someone to programming, I promise to never bring them within 2 alt+tabs from php. Enough has been said about why php isn’t quite exactly the best tool (although there never really is a ‘best’ language) but it should be kept in the highest shelf until someone is knowledgeable enough. Think of it as the Jack Daniels of web-development (never bring it out on the first night!).

To cut to the chase, I needed to design a forum of some sort but with confusing privileges. The website was a simple one but with one small problem; it wasn’t meant to be a forum. There is a web-analytic procedure that is simply known as the goal of a website. For blogs or news websites, we just want to have page views. The more the merrier. There are some variations in there but generally page count is the bottom line. For social networking sites, you need average time spent on the website (and some variations of it). The problem with the website like the one I worked on, is it had no particular goal or at least a way of measuring that goal. Would we need to create one username/password for the entire forum? Would we need to recreate an entire forum, with usernames and all the privileges associated, for a website that is used by less than 20 people? Surely email/social networks could have done a much more efficient job. After 2 weeks or so of learning php, I decided to request help from a Nordic kid who knew far more php than I could ever hope. After seeing his solutions, it suddenly hit me. I dove too deep too quickly. I had no idea what I was doing at this point.

Web development (and programming in general) isn’t something you only learn parts of it. This is especially true for someone like me who always tries to understand every single section within a system. You can’t learn html & css and call it a day. You will need some javascript (and by extension jquery and other jscript libraries), then slowly you’ll find yourself trying to understand php and SQL. You keep digging deeper and deeper, and if you aren’t careful, you appear utterly lost. The funny thing is that you never are lost. If you meant to be in a forest, as long as you are in it, all shall be fine. This differs quite a lot from a lot of other fields due to heavy reliance between different sections. A lot of newbies start with the idea that they are learning “Web Design”. After a session with CSS, not many want to see the first $echo statement. There are more ways to do the same thing than one could imagine. And they are all perfectly fine. This can get confusing and frightening abruptly. It appears different because other fields get narrower and narrower as you go deeper (I like to imagine it as a funnel). Web development is like an inverted funnel. The more you learn, the more you realize how more you need to learn. This can act as a deterrent to most novices (especially for those who prefer the funnel approach).

I’m working on an actual real life project that frightens me at the moment. At times I need to remind myself how to break the cognitive dissonance. It is challenging to know when exactly to flip the switch from thinking in one way to the other when you stare at the glowing back-light from the monitor.