
Eric Stanley- 23 Oct, 2019
Higher order functions
I recently started learning JavaScript and I tumbled upon a concept called Higher Order Functions (HOF). There are quite a lot of documents in the internet that explains what an HOF is, and here is my thought. Before explaining what an HOF is, let’s see how a function looks like in JavaScript. Functions in JavaScript is not different from functions in any other programming languages, which means, I assume that you kinda know how a function generally looks like. Below is a function snippet in JavaScript. function myTestFunction() { alert("Thanks for clicking") }Now, that we know how a function looks like in JavaScript, let’s continue on knowing what HOF is and how is it different from a normal function. HOF is a concept in JavaScript where a function (say x) is passed as an argument to another function (say y) OR the calling function (say z) returns a function (say x) after execution Let’s take the above function for example (#1), and pass it into another function document.addEventListener("click", myTestFunction) function myTestFunction() { alert("Thanks for clicking") }Now, document.addEventListener is called whenever an event in the first parameter is triggered in the document, and the second parameter is a function that gets executed whenever the event is triggered In other words, the above function can also be written as document.addEventListener("click", function myTestFunction() { alert("Thanks for clicking") })And this works perfectly fine. So, if this works perfectly fine, why would I need to write another function and call it within the addEventListener instead of writing directly within the listener. The answer is, the function can be reused now, if it’s outside the listener. Kinda makes sense? Let’s take another step and look at another example (#2) which is a little more complex. function createMultiplier(multiplier) { return function(x) { return x * multiplier } }let doubleMe = createMultiplier(2) let tripleMe = createMultiplier(3) let quadrupleMe = createMultiplier(4)document.write(doubleMe(45) + "<br>") document.write(tripleMe(45) + "<br>") document.write(quadrupleMe(45) + "<br>")As you can see, the createMultiplier function returns a function here which can be used in different places. Let’s take a look at how the code looks without HOF function multiply(x, multiplier) { return x * multiplier }let doubleMe = multiply(45, 2) let tripleMe = multiply(45, 3) let quadrupleMe = multiply(45, 4)document.write(doubleMe + "<br>") document.write(tripleMe + "<br>") document.write(quadrupleMe + "<br>")Looks like, the code without HOF is still less number of lines and effective too! Until now, even I was not sure about the use of HOF. But let’s take 1 more step from here. Let’s parameterize the multiplier (#3) With HOF function createMultiplier(multiplier) { return function(x) { return x * multiplier } }let nums = [41, 42, 43, 44, 45, 46]let doubleMe = createMultiplier(2) let tripleMe = createMultiplier(3) let quadrupleMe = createMultiplier(4)for (i = 0; i < nums.length; i++) { document.write(doubleMe(nums[i]) + "<br>") document.write(tripleMe(nums[i]) + "<br>") document.write(quadrupleMe(nums[i]) + "<br>") }Without HOF function multiply(x, multiplier) { return x * multiplier }let nums = [41, 42, 43, 44, 45, 46]for (i = 0; i < nums.length; i++) { let doubleMe = multiply(nums[i], 2) let tripleMe = multiply(nums[i], 3) let quadrupleMe = multiply(nums[i], 4) document.write(doubleMe + "<br>") document.write(tripleMe + "<br>") document.write(quadrupleMe + "<br>") }As you can see, the numbers 2, 3 and 4 are constants and we are not making any changes to those parameters within the loop. However, we cannot move them outside of the for loop since the resultant value is dependent on this constant. Whereas, in the code with HOF, we have moved the constants successfully outside of the loop. Now, why do we do that? Does it impact the performance? The answer in this case is, the code looks a little bit neat and NO it does not affect the performance. Here’s another example of HOF in JavaScript let myColors = ["red", "orange", "yellow", "green"] myColors.forEach(saySomethingNice) function saySomethingNice(color) { document.write("The color " + color + " is a great color. <br>") }The forEach method in the array object automatically loops thro’ every element in the array without using a loop, which means less code to do the same work. The code in example #3 looks like this now! function createMultiplier(multiplier) { return function(x) { return x * multiplier } }let nums = [41, 42, 43, 44, 45, 46]let doubleMe = createMultiplier(2) let tripleMe = createMultiplier(3) let quadrupleMe = createMultiplier(4)nums.forEach(num => { document.write(doubleMe(num) + "<br>") document.write(tripleMe(num) + "<br>") document.write(quadrupleMe(num) + "<br>") })In my personal terms, if you are a novice JS developer and if you copy and paste a code in JavaScript which you feel that it’s hard to understand, but still works the way you wanted it to, you are probably looking into a HOF. That’s my personal view of HOF though! Ending Note: The latest JavaScript ES6 standard, has tackled a lot of limitations that the ES5 standard had, and HOF is one of those.

Eric Stanley- 12 Oct, 2019
Binary Search
Before we get into the syntax and logic of binary search algorithm, let’s ask ourselves this question. Why do we need binary search at all in the first place? To understand, let’s work with an example here. Let’s say you were given a name in a letter pad (say ‘Michael’) and you were asked to find that person from a group of 50 people who are standing by name order i.e., Adam stands first, then Alex, then Bob and goes on. You get the idea. Now, what you do is, pick the 25th person and ask his/her name. Let’s say the person’s name is ‘Monica’. Now you know that ‘Michael’ is somewhere before ‘Monica’ as everyone is standing in ascending order. The reason I picked the 25th person, is coz’ picking that person would give me the max reduction. In the sense, I can ignore the other 25 people after ‘Monica’, since; I know that ‘Michael’ cannot come after ‘Monica’. The idea is filtering 50% of the wrong choices in every question you ask, will give you the fastest route to the destination. To make it clearer, let’s say I pick a random number (say 35) instead of picking the 25th person. I ask the 35th person, what his/her name is? Now there are two possible outcomes. Either his/her name can be ‘Stuart’ or ‘Henry’. Now, you have a 50 percent chance that you might get either one of these names. If the person says ‘Henry’ then you are lucky, coz’ you only need to filter remaining 15 people to find out your match, but guess what, what if the person’s name is ‘Stuart’, you just got burned here! In other words, instead of filtering from your best bet number, which is 25, now you need to filter from 35. Hope you get the reason why you need to filter by half every time to find the quickest way to find your match. If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of 35 iterations, which means with asking 35 questions, you will be able to find the person that you are looking for. Isn’t that cool! Hence, always try to order your array or collection in some way and make sure to index it i.e., if you are adding a row in your excel spreadsheet which you know that the records are gonna increase in the course of time, make sure to add a serial number to each row, so that you can order by ascending/descending anytime to sort the list and, once the list is sorted, perform the binary search to find the record you need. So, to answer the question ‘why’, binary search algorithm is one of the fastest way to find a random number in a set of indexed numbers, instead of searching the numbers sequentially. Now that’s why! Alright, funz over. Let’s get to work now. Below is the program to implement binary search in VB Script Dim testarr(100000) Dim n, i, resn = 5643For i = 1 To 100000 testarr(i) = i Nextres = CStr(binser(testarr, n)) Wscript.echo resFunction binser(arr, tar) Dim low, high low = LBound(arr) high = UBound(arr) iter = 0 Do While low <= high i = Round((low + high) / 2) If tar = arr(i) Then binser = True Wscript.echo iter Exit Do ElseIf tar < arr(i) Then high = i - 1 Else low = i + 1 End If iter = iter + 1 Loop If Not binser Then binser = False End IfEnd FunctionNote: Binary search works only with sorted arrays, it just won’t work in case of unsorted arrays. Imagine the people are standing in unsorted order in the above example, in which case, you just got double burned! And the odds of finding a person (out of 50) is you gotta ask atmost 49 questions to find the person who you are looking for. You gotta be really lucky otherwise!

Eric Stanley- 13 Sep, 2019
Game Show Host Problem
The game show host problem which is also called as ‘Monty Hall Problem’ is one of the classic math puzzle, which best explains the odds of probability. A game show host and a player (you/me) are the ones who are involved in this puzzle. The puzzle has 3 doors out of which 2 doors will have nothing in it and 1 door will have the treasure, which the user is intended to find. The game show host first asks the player to pick a random door. Let’s say the player picks the door number 1. Now, the game show host opens door number 3 and reveals that the 3rd door has nothing in it. After which, the host asks the player whether he/she likes to change the answer. Let’s get into the math now, before answering the host’s question. Considering the initial odds that the user had which is 33.33% chance of hitting the correct door, which has the treasure. Now, how I got this 33.33%? Alright, let’s say there is only 1 door, which has the treasure, and the host asks to pick the door that has the treasure. Now, that there is only 1 door, there is no choice for you/me to pick the wrong door. Which gives the probability of finding the correct door is 100% (1 out of 1 door). In case of 2 doors, the probability reduces to 50% (1 out of 2 doors) and 33.33% in case of 3 doors. That’s how I got the 33.33% Now that we know the initial odds, let’s check the new odds after the host asks the player if he/she wishes to change the door. There are only 2 possible answers to this question. You can either change the door or stick with the door that you/me chose initially. Let’s check the probabilities for either of these answers, so that we can understand how the odds change based on the choice that we make. It’s easy to assume that the odds to finding the right door after the question is 50%. Coz’, after the opening the 3rd door, we only have 2 doors to open out of which 1 door has the treasure, which makes the probability to 50%. However, what we are ignoring here is the initial odds (probability). Let’s see how the initial probability changes the odds of the outcome of the host’s question. Let’s first assume that we are not changing the door and we are sticking with the door # 1. In which case, the chances of winning the treasure is still 33.33%. Which means, whether or not the host asks the question, we are not using it effectively to increase our chances to win. The probabilities before and after the question still stays the same and that means we had 33.33% chance to win the prize and we have the same percentage of probability now. Now, what happens if we change the door? We know that door # 3 has nothing, so if we plan to change door now, we have nothing else but door # 2. Considering the initial odds (33.33%), let’s calculate the odds of winning the treasure now. Though, the door with nothing in it (door # 3) was opened, we now have a choice to open 2 doors instead of 1 door if we change our answer. Door # 3 is already open, and we are opening door # 2. Otherwise, we are opening only 1 door (door # 1) irrespective of the door already opened. Meaning, the host has already given us an extra 33.33% by opening the door with nothing in it and if we change the door now to door # 2, we have a 66.67% chance of hitting the right door (opening 2 out of 3 doors). Remember, no host wants the player to win. So, the host is always going to open the door with nothing in it, coz’ there are 2 doors which has nothing in it, which means irrespective of whether you pick the correct treasure door or a wrong door, the host will always have the option to pick the door which has nothing in it. It’s was quite hard to explain this problem in plain text than I thought, but if you get this right. Watch out for the odds next time!

Eric Stanley- 21 Aug, 2019
Ternary Operators
The ternary operator is basically another way to implement the if-else statement. Now, if it’s just another way to implement the if-else statement, why can’t I use the same old if-else? Why would I need to take up something extra which I don’t need right now? As for any new change, the answer to the above question is simple. Kinda hard, but it’s worth it. It’s not absolutely necessary to learn it, as you can do anything and everything without it. However, considering the constant evolution of technology, it’s better to learn new things while we still can! After all, learning new things is always interesting. Let me put this straight. This post is not to blame on the good old if-else statement. If you are not clear on the if-else statement, I would recommend you to google it before you proceed further. Before we get into what a ternary operator is, let’s get a quick bite on what an operator and operand is, and different kinds of operators in general Operator: These are the symbols that we use in our calculations. Ex: + - / = * % Operand: These are the variables or constants the are being used with the operator for calculations There are 3 different types of operatorsOperator DescriptionUnary Operators Requires one operand. Ex: a++Binary Operators Requires two operands. Ex: a+bTernary Operators Ternary Operators: Requires three operands Ex: c ? a : bLet’s start with a simple example as usual. A typical if statement looks like below if (latitude > 0) { return 'summer' } else { return 'winter' }Let’s put the above statement in a function, so that we can see the actual working result function getSeason(latitude) { if (latitude > 0) { return 'summer' } else { return 'winter' } }document.write(getSeason(10))If you want to see how the above code works, I would recommend codepen.io, however if you already know how this works; or, you already are part of another online code editor community, good for you 🙂Moving on, the getSeason function takes one argument which is the latitude and returns a season string based on the latitude. Ternary operators are all about reducing the number of lines of code. So, before implementing the ternary operator, let’s see if we can reduce the number of lines without it. If the if-else statement has only one line of code to be executed, then the {} is actually not necessary. The above code can be written as function getSeason(latitude) { if (latitude > 0) return 'summer' else return 'winter' }document.write(getSeason(10))Not much of code reduction here, but the point is, you can avoid the {} in case of one statement within the if-else block Note: Anything more than one statement within the if-else would require the {} Time to implement ternary operator in our above example. function getSeason(latitude) { return latitude > 0 ? 'summer' : 'winter' }document.write(getSeason(10))Looks like the code is reduced a lot now, but how about nested if statements. Let’s take a look at a little more complex example by adding another variable called month to derive the season, like below function getSeason(latitude, month) { if (latitude > 0) { if (month >= 1 && month <=6) { return 'summer' } else { return 'winter' } } else { if (month >= 1 && month <=6) { return 'winter' } else { return 'summer' } } }document.write(getSeason(10, 5))As you can see, the code is a lot more complicated and the number of lines has significantly increased this time. Good news, is the ternary operator can be nested too. The above example can also be written as function getSeason(latitude, month) { return latitude > 0 ? (month >= 1 && month <=6) ? 'summer' : 'winter' : (month >= 1 && month <=6) ? 'winter' : 'summer' }document.write(getSeason(10, 5))Now, all the code in the nested if-else example can be written just in one single line. On a side note, we can get the current month and current latitude programmatically. The final code now looks like below function getSeason(latitude, month) { return latitude > 0 ? (month >= 1 && month <=6) ? 'summer' : 'winter' : (month >= 1 && month <=6) ? 'winter' : 'summer' }new Promise((res, rej) => navigator.geolocation.getCurrentPosition(res, rej)).then(pos => document.write(getSeason(pos.coords.latitude, (new Date().getMonth()+1))))Make sure to click on Allow when you get the prompt for requesting access to location. Now what is the new statement that I have written to extract the current month and latitude? Well, that is to be discussed in another post! Stay tuned!