DEV Community

Cover image for Interesting Things About Javascript Arrays
Marcell Cruz
Marcell Cruz

Posted on

Interesting Things About Javascript Arrays

A handful of interesting facts about javascript arrays.

A javascript array is just an object.

let arr = [1, 2, 3];
let arr2 = {
  '0': 1,
  '1': 2,
  '2': 3
}
Enter fullscreen mode Exit fullscreen mode

The only difference is that arr inherits from the Array prototype so it has all the array methods(map, reduce, etc...) and the length property.

You can create new properties

Because Arrays are just objects, they're slow when compared to arrays in other languages and you can create new properties.

arr.total = function() {
  return this.reduce((acc, i) => acc + i, 0)
}
console.log(arr.total()); // 10 
Enter fullscreen mode Exit fullscreen mode

The length is not necessarily the length

It's just the last element index + 1;

let countries = [];
countries[1000] = 'Brazil';
console.log(arr.length); // 1001 🤷
Enter fullscreen mode Exit fullscreen mode

You can change the length directly

You can remove elements in an array just by changing the length

let arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log(arr); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

You can also add new slots just by changing the length of the array.

let arr = [1, 2, 3, 4];
arr.length = 100;
console.log(arr); // [1, 2, 3, 4, 96 empty items]
Enter fullscreen mode Exit fullscreen mode

No index out of bounds errors

You don't have index out of bounds errors in javascript, any index not initialized or non-existent it will return undefined.

let arr = [1, 2, 3];
console.log(arr[999]); // undefined
Enter fullscreen mode Exit fullscreen mode

Map is not called on empty items

Map, filter, reduce, etc.. doesn't work in empty(not initialized) items

let arr = Array(5); // [5 empty items] 
arr = arr.map(() => 1);
console.log(arr); // [5 empty items]
Enter fullscreen mode Exit fullscreen mode

empty !== undefined

Empty is not the same as undefined, in other words, an index with an undefined item is not empty.

let arr = [undefined, undefined];
arr = arr.map(() => 1);
console.log(arr); // [1, 1]
Enter fullscreen mode Exit fullscreen mode

But if you query for an empty item the returned value is always undefined

let arr = new Array(3);
console.log(arr[2]); // undefined
Enter fullscreen mode Exit fullscreen mode

Initializing items

You can initialize all object with Array.from

let arr = Array.from(Array(10));
arr = arr.map(() => 1); // map will work now
// Array.from can receive a second argument that is a map
let arr = Array.from(Array(10), () => 1);
console.log(arr); // same result as above without creating the intermediate array
Enter fullscreen mode Exit fullscreen mode

If you have any more interesting facts about javascript arrays please leave a comment :)

Top comments (0)