Glossary / Arrays

Arrays

JavaScript arrays are ordered, integer-indexed objects with a length property and a rich set of iteration and transformation methods. They are optimized for sequence-like data, but remain dynamic: they can grow, shrink, hold mixed values, contain holes, and carry non-index properties. An array reference can be mutable even when declared with const.

Mutation and transformation

Mutating methods include push, pop, splice, sort, reverse, and fill. Methods such as map, filter, slice, concat, and newer copying methods return a new outer array, though elements that are objects remain shared references. Know the method contract before using it in state-management code.

const values = [10, 2, 30];
values.sort(); // [10, 2, 30] here, but ordering is string-based
values.sort((a, b) => a - b); // numeric order

Default sort converts values to strings and compares UTF-16 code units; supply a comparator for numeric or domain order. Comparators should be consistent (antisymmetric/transitive) to produce reliable ordering. Methods differ in how they handle sparse holes; dense arrays are usually easier to reason about. Array indices are property keys, and length is one more than the highest present array index, not necessarily the number of present elements.

Complexity and practical use

Choose arrays for ordered sequences and positional access; use Map/Set for keyed lookup or uniqueness. Repeated front insertion/removal can require shifting elements. For large lists, consider algorithmic complexity, allocation, and virtualization at the UI layer. Validate arrays from external data and avoid assuming a homogeneous shape unless the contract guarantees it.

Interview questions

  1. Does sort() sort numbers numerically by default? No; default comparison is string-based.
  2. Does map deep-copy objects? No; new array, same object element references.
  3. Which common methods mutate? Push/pop/splice/sort/reverse/fill mutate; verify the specific method.
  4. Is length the count of actual elements? Not for sparse arrays; holes count toward length.

References