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
}
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
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 🤷
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]
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]
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
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]
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]
But if you query for an empty item the returned value is always undefined
let arr = new Array(3);
console.log(arr[2]); // undefined
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
If you have any more interesting facts about javascript arrays please leave a comment :)
Top comments (0)