JavaScript Arrays Explained: Engineering Insights

Arrays Engineering Side

Β·

2 min read

In this article we will discover the essence of JavaScript arrays as we explore continuous and holey arrays, alongside optimization strategies like SMI (Small Integer), Packed Element, and Double formats. Through examples like arrOne, we'll unravel the intricacies of array structures and optimization techniques, empowering you with insights for efficient JavaScript coding.

Arrays in JavaScript

  1. Continous

  2. Holey

Optimisation of arrays : SMI(Small Integer) , Packed element , Double(float, string, function)

Examples:

const arrOne=[1,2,3,4,5] //PACKED_SMI_ELEMENTS (no hole in it)

Note: It is a specific type so only numbers are allowed(1,2...)

arrOne.push(6.0) //PACKED_DOUBLE_ELEMENTS

Note: The optimisation type has been changed to PACKED_DOUBLE ; we cannot go back to PACKED_SMI_ELEMENTS even if we delete that element 6.0

arrOne.push('7') //PACKED_ELEMETS

arrOne[10]=11 //HOLEY ELEMENTS (as gap is present in it)

print(arrOne) -> [1,2,3,4,5,6,'7',<3 empty items>,11]

print(arrOne.length) -> 11

print(arrOne[9]) -> undefined(costly operation)

print(arrOne[12]) -> undefined

How array find index value?

(1) bound check -> if index >=arr.length

(2) hasOwnProperty()

hasOwnProperty(arrOne,9)

hasOwnProperty(arrOne.prototype,10)

hasOwnProperty(Object.prototype,10)

Note: hasOwnProperty() check is very expensive in JS as holes are very expensive in JS

const arrTwo=[1,2,3,4,5]

arrTwo[8] -> out of bound

arrTwo[2] -> 3

Order of Optimisation

SMI>DOUBLE>PACKED (Continous)

H_SMI>H_DOUBLE>H_PACKED (Holey)

Note: Once optimisation downgraded , it cannot be reversed

Example : If array optimisation type changes from SMI to double , then we cannot get back to SMI type

const arrThree =new Array(3) //just 3 holes => HOLEY_SMI_ELEMENTS (initially)

arrThree[0]='1' //HOLEY_ELEMENTS

arrThree[1]='2' // HOLEY_ELEMENTS

arrThree[2]='3' //HOLEY ELEMENTS

Better Approach

const arrFour=[] //PACKED_SMI_ELEMENTS

arrFour.push('1') //PACKED_ELEMENTS

arrFour.push('2') //PACKED_ELEMENTS

arrFour.push('3') //PACKED_ELEMENTS

IMP : const arrFive=[1,2,3,4,5]

arrFive.push(NaN) //PACKED_DOUBLE

Note: for, for...of , forEach -> prefer inbuilt JS Methods

Β