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


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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771987353/QCWK6tjWl.png)

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
```


![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771989721/xWvJZK9m7.png)

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](https://medium.com/@tanyagupta/i-dropped-my-cs-major-because-i-couldnt-do-a-bubble-sort-126e1242d86e#.aohwtloii)) 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](https://www.tutorialspoint.com/data_structures_algorithms/linear_search_algorithm.htm) 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.

## 1) Array.indexOf()

The [Array.indexOf() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) 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](https://medium.com/@neversleep) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) returns true or false based on whether an array includes a certain element.)

Here is a simple use case for Array.indexOf():

```javascript
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
  
}
```

## 2) Convert the array to an object literal and use the “in” operator

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; 
}
```


![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771991214/B07wz7l-o.png)

### Recommendation: use Array.indexOf() — easier andshorter

![Courtesy: [Pixabay](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771992388/xhHcT3-Ie.html)](https://cdn-images-1.medium.com/max/2000/1*YJmKqYHIMiiPcMBDtuG5hw.jpeg)*Courtesy: [Pixabay](https://pixabay.com/en/binary-system-code-computer-files-1543168/)*

## An experiment to determine speed

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

1. For every size of arrays that I created:

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..*

## Try { there are significant efficiency gains}

The graph and the table below shows that either of the two methods are way faster than the linear search.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771993699/dIBYHpJtp.png)

**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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771995012/3FdXG6w7c.png)

![Speed test](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771996320/1xcVnkpOM.png)*Speed test*

## Catch with the hack{We bomb if the arrays are not known at coding time}

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.

### Bottom line: Use Array.indexOf() — will fit for most use cases unless you are dealing with large sizes and you have some knowledge of the arrays at coding time.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1630771997585/mjJM9DCuo.gif)
