Tuan-Anh Tran

Things you may not know about JavaScript array

Posted on July 28, 2014  •  1 minutes  • 197 words

Let’s begin with creating an array.

arr = [1,2,3];
typeof a;
> "object"

you get object. Wow, so how would I check whether it is an array? Here’s how people usually do it.

if ('[object Array]' === Object.prototype.toString.call(arr)) {
  // your code
}

Next, what if I’m trying to access index that is greater than current length?

arr[10] = 10;

Seems ok!? No index out of range error whatsoever !? Let’s take a look at it again.

> [1, 2, 3, undefined × 7, 100]

Looks like JavaScript automatically expands the array and filled the blank with undefined.

What about if I’m trying to shrink the array

arr.length = 1;
> [1]

JavaScript reduces the size and keeps only elements from 0 to new length.

What if I try something like this

arr['hello'] = 100;
> [1]

Hmm, where is hello? Let’s try to access it again

arr['hello'];
> 100

Phew, it’s still there.

Ok, let’s stop making fun about JavaScript here for now. No matter how you see it, JS is a pretty good language. I kinda the language in general but some stuff, it’s just weird!! Though I have to admit, it’s fun to debug.

Follow me

Here's where I hang out in social media