Encountering Javascript’s “weird” parts as a noob and how I dealt with it

Search for a command to run...

No comments yet. Be the first to comment.
Disclaimer: Consistent with the honor code, no solutions are provided here, only hints to help troubleshoot two common errors While working on the Deep Learning capstone “Deploying a Sentiment Analysis Model” project, most of my time was spent troubl...

Over the past several months, I’ve had the fortune to develop Apps for Google Chromestore and one app that has more than half a million users (here’s my story, and be selected for Udacity’s Grow with Google. As a part of this scholarship I got the ch...

This blog is about new ES6 features. Learning about ES6 is probably pretty straightforward for experienced folks. It wasn’t for me. As a part of Udacity’s Grow with Google challenge cohort where ES6 was covered, I see that I wasn’t alone. So here are...

Udacity sponsors a three month first round “Grow with Google Challenge Scholarship”. When I applied to the Mobile Web Specialist track I was not sure what I would get out of Udacity. I considered myself a middling self-taught web programmer. (Here’s...

This post is about two ways to handle pagination (getting multipage results) in response to queries on Google and Zendesk APIs While most Web API provides multi page results to a call, most API documentation will only talk about how to get the first ...

Array.indexOf() and converting an array to an object literal

The weirdness of Javascript is hard enough to deal with if you are an experienced programmer. It is much harder for a new programmer.
My first encounter with Javascript’s strangeness was with the in operator. The in operator is a nifty tool to check if a specified property is present in a specified object. For example we can check if a certain key is present in a object that has several key value pairs.
var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar // returns true
"mileage" in mycar // returns false
Unfortunately the in does not work in an intuitive (and useful) way when used with arrays.
In the example below, I would really like it if Javascript’s in would work like this:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
"bay" in trees // returns false

The reason it does not work (and it should not) is the particular way Javascript’s array objects are implemented. They are internally viewed as a key value pairs of index and the corresponding element. For example the trees above is stored internally as something like:
{0:"redwood", 1:"bay", 2:"cedar", 3:"oak", 4:"maple"}
And yes, 1 in trees will return true, but that is not useful to me as a programmer.
I am relatively new to programming (here’s my story in medium) and I do not code professionally. But even I encounter several scenarios almost every day where I need to check if some item is in an array or not. Naturally this weirdness in Javascript puzzled me a bit. From what I found out, this is available in other languages (Python, Ruby) so — why not Javascript? I googled a bit and found this on how to implement a “linear search” in Javascript. Which I did.
To check if an item is in an array, I have to iterate through the array elements until the item is found in the array.
function inArray (item, theArray) {
var found = false;
var i=0;
while (!found && i in theArray) {
found =(item === theArray[i]);
i++;
}
return found;
}
But it was not satisfying. I could not tell then what exactly about it dissatisfied me — at that point it was just something I did not think was cool. I now know better. Please read on.
The Array.indexOf() method returns the first index at which a given item can be found in the array. If it is not present it returns -1. Thanks to Nikolay Digaev for pointing me to this (another is Array.includes() — which unfortunately is not currently supported by Google Apps Script where I mostly work on these days. The Array.includes() method returns true or false based on whether an array includes a certain element.)
Here is a simple use case for Array.indexOf():
function item_in_array(){
var fruits = ["Bob", "Rob", "Amanda", "Cheryl","Susan"];
Logger.log(fruits.indexOf("Susan")) //returns 4 which is the index of Susan
Logger.log(fruits.indexOf("Frank")) //returns -1 since the item is not found
}
I figured out a way to use the in operator in my use cases. I started converting my arrays to objects. I would store each (unique) item as a key and just put a blank in the corresponding value.
The Hack: convert the array to a typical object with items as keys and empty values
**Creating the object:**
var hack_object_literal = {};
for (var i in test_data) {
hack_object_literal[test_data[i]]="";
}
Careful readers may notice that my hack ignores duplicate items when building the object. Which is fine since all we want to know if an item is present. Not how many of them are present.
Now I can use the in operator to check if the item is present in the object which in effect tells me if the item is present in my array.
function inArrayMyHack (item, arrayDataAsObject) {
return item in arrayDataAsObject;
}

Courtesy: Pixabay
Computer science purists believe that data structures should be used for the tasks they are originally designed to do, as otherwise, it results in unmaintainable code. One may deviate from this principle only if there is a compelling reason to do so. Leaving the values empty in a collection of key-value pairs seem to be a major deviation. So I decided to see if there is a compelling reason for my “hack.” And I found it.
I implemented the three functions: the linear search function as inArray, Array.indexOf() and inArrayMyHack
a) I sorted the array element and created a sorted version of the array
b) For every element in the sorted array I called both the functions giving them the element and the array. So for a 200 size array both the functions will be called 200 times each.
I recorded the time it took for them to complete.
Note for inArrayMyHack I also had to convert the array to an object before I made the call. I added that time to the performance time of inArrayMyHack — but there is a catch to that to0, read on..
The graph and the table below shows that either of the two methods are way faster than the linear search.

The hack and Array.indexOf() are close initially but the Array.indexOf() methods slows down once size increases. I talked to some coder friends who told me that the reason for this performance is the in operation uses a very fast algorithmic technique called hashing. This technique produces a performance that is (almost) constant time regardless of the data size. Linear search time increases as the data size increase. The data conversion time is very negligible compared to the speed gained by hashing.

Speed test
There can be situations where I do not know about the arrays at coding time. In such case I will not be able to convert the arrays to objects before making the call. Things will slow down if I have to do a lot of searches each time with a different unknown array.
