QuestenaPractice that shows what to review next
Topic lesson

Arrays: track indexes, mutation, and sharing

About 6 min

Questions stay in the language in which they were published.

These questions ask you to follow array indexes, sparse length, reads, insertion and removal methods, copying, and destructuring. Keep three notes as you work: which positions are present, whether the source changes, and what value the expression returns.

Model the positions before the method

Ordinary array positions begin at zero. For a nonempty array, length is normally one more than the highest present index unless length was explicitly enlarged. Assigning beyond the current end raises length to the assigned index plus one, while skipped positions are holes rather than automatically stored null or undefined values. Reading either a hole or an out-of-range position produces undefined, but that result alone cannot prove the position is absent because an element may explicitly hold undefined.

OperationMutation and return procedure
push and poppush adds at the end and returns the new length; pop removes and returns the last element. If [] receives pop, the result is undefined.
shift and unshiftshift removes and returns the first element; unshift adds at the beginning and returns the new length. All four end methods mutate their array.
sliceSelect a range into a new array without changing the source. ["p", "q", "r"].slice(0, 2) creates ["p", "q"].
spliceInsert, replace, or remove inside the source, then return an array of removed elements. Record the source and returned array separately.
Array.isArrayUse Array.isArray(value) to distinguish arrays from ordinary non-array objects. typeof labels both as object, and a length property proves nothing.
spread and destructuringSpread creates a new outer array but reuses nested object references. A pattern such as [head, , tail] reads by position, skips one binding, and does not remove anything from the source.

The tempting wrong routes

Try it

Question 38

Starting from an empty array, values are assigned only at indexes 0 and 4, and no other length-changing operation occurs. What is its length?

  1. 2
  2. 5
  3. 4
  4. undefined
Question 45

Which statements about Array splice are true? Select all that apply.

  1. It never changes its source array
  2. It always returns the final array length
  3. It can insert or remove elements
  4. It returns an array of removed elements
Question 47

A shallow array copy is made with spread from an array containing a nested object. What is shared between source and copy?

  1. The nested object reference
  2. The outer array identity
  3. Nothing at any depth
  4. Only the length property object
Start drillPractice this topic
Arrays: track indexes, mutation, and sharing · Questena