JavaScript Arrays
(Part 11)
Array
Arrays are NOT a separate primitive type. They are specialized objects. Internally, arrays are among the most complex built-in structures in JavaScript engines. The engine tries to store its elements in the contiguous memory area, one after another.
const arr = [1, 2, 3];Arrays are:
- objects
- iterable
- indexed collections
- dynamically sized
- highly optimized by engines
- capable of becoming sparse/dictionary-like
typeof [] //objectArrays internally behave roughly like object with extra array-specific behavior
{
"0": value,
"1": value,
"2": value,
length: 3
}Array indexes are property keys internally.
Declaration
There are two syntaxes for creating an empty array:
let arr = new Array();
let arr = [];let fruits = ["Apple", "Orange", "Plum"];
Read
fruits[0] // "Apple"
Replace
fruits[0]="Banana"
fruits[0] // "Banana"
Add
fruits[3] = 'Lemon'; // now ["Banana", "Orange", "Plum", "Lemon"]An array can store elements of any type.
let arr = [ 'Apple', { name: 'John' }, true,
function() { alert('hello'); } ];
arr[1].name; // John
arr[3](); // helloAn array, just like an object, may end with a comma,The “trailing comma” style makes it easier to insert/remove items, because all lines become alike.
let fruits = [
"Apple",
"Orange",
"Plum",
];ARRAY MEMORY MODEL
Arrays are reference types. Assignment copies Reference not array.
const arr = [1, 2, 3];
Stack
arr ─────► 0x100
Heap
0x100:
{
"0": 1,
"1": 2,
"2": 3,
length: 3
}const a = [1,2];
const b = a;
b[0] = 99;
a[0] // 99LENGTH PROPERTY INTERNALS
length is very special. Length is not an actual element count it is highest index + 1
const arr = [1,2,3];
console.log(arr.length); // 3const arr = [];
arr[100] = "x";
console.log(arr.length); //101
index 0 → empty
index 1 → empty
...
index 100 → "x"
length = 101Array length depends on highest numeric index.
DENSE VS SPARSE ARRAYS
Dense Array: All indexes filled.
[1,2,3]SPARSE ARRAYS: Many holes.
const arr = [];
arr[100] = 1;Sparse arrays are slower internally.
Why do sparse JS arrays become slower?
Get Shubham Gupta’s stories in your inbox
Join Medium for free to get updates from this writer.
JavaScript engines optimize dense arrays differently.
Dense arrays: [1,2,3,4]
can use fast contiguous storage optimizations.
But sparse arrays: arr[1000000] = 5 contain many holes.
The engine may switch internally from packed array optimization to dictionary/hash-like storage
This reduces iteration and access efficiency.So sparse arrays may become slower.
HOLES VS UNDEFINED
Explicit undefined
const arr = [undefined];Hole
const arr = [,];THEY ARE NOT THE SAME
0 in [undefined] //true property exists with undefined value
{
"0": undefined
}
0 in [,] //false property does not exist
{
}New Array()
There is one more syntax to create an array:
let arr = new Array("Apple", "Pear", "etc");It’s rarely used, because square brackets [] are shorter. Also, there’s a tricky feature with it.
If new Array is called with a single argument which is a number, then it creates an array without items, but with the given length.
new Array(5)
[ <5 empty items> ]
it creates holesclassic issue
new Array(5).map(() => 1)
[ <5 empty items> ]
//map skips holes.to solve this we do have another method Array.from()
DELETE VS SPLICE
DELETE
Length remains unchanged. Creates hole
const arr = [1,2,3];
delete arr[1]; // [1, empty, 3]SPLICE
Indexes shifts.
arr.splice(1,1); //[1,3]PUSH/POP (add/remove element from the end)
Push used to add an element at the end
const arr = [1,2,3];
arr.push(10)
Internally roughly:
arr[arr.length] = 10;
arr.length++;Pop removes the last element and decreases the length. Extracts the last element of the array and returns it
const arr = [1,2,3];
let a= arr.pop() //3 removed element returnedSHIFT/UNSHIFT (add/remove element from start)
Shift removes the element from the start
const arr = [1,2,3];
arr.shift() //1
[1,2,3] Indexes changed.
↓
[2,3]unShift Adds the element to the beginning of the array
let fruits = ["Orange", "Pear"];
fruits.unshift('Apple');
alert( fruits ); // Apple, Orange, PearMethods push and unshift can add multiple elements at once:
let fruits = ["Apple"];
fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");
// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
alert( fruits );If you’d like to be in the know, subscribe, clap, like and share. Cheers!







