Question Bank
JavaScript Array Method Output Traces
Difficulty: Medium
Six traces drilling on in-place vs returning array methods: `reverse`, sparse arrays, `indexOf`, `filter(Boolean)`, default lexicographic `sort`, and `copyWithin`.
JavaScript Array Method Output Traces
Six traces drilling on in-place vs returning array methods: `reverse`, sparse arrays, `indexOf`, `filter(Boolean)`, default lexicographic `sort`, and `copyWithin`.
193 views
6
What do both console.log calls print, and why does mutating arr2 also mutate arr1?
Examples
Example 1:
Input: log(arr1); log(arr2);
Output: ['n', 'h', 'o', 'j']; ['n', 'h', 'o', 'j']
Explanation: Array.prototype.reverse mutates the original array in place and returns the same reference, so arr1 and arr2 point to the same reversed array.What does arr.length print, and why does delete leave it at 11?
Examples
Example 1:
Input: console.log(arr.length)
Output: 11
Explanation: Assigning arr[10] extended length to 11, and delete only removes the property at index 10 without shrinking the array length.What does each console.log print? Pay attention to the fromIndex argument of indexOf.
Examples
Example 1:
Input: arr.indexOf(2); arr.indexOf(4, 5); arr.indexOf(2, 3);
Output: 1; -1; 9
Explanation: indexOf(value, fromIndex) returns the first index >= fromIndex matching strictly, returning -1 when no such index exists.What does this code print, and what survives the filter(Boolean) call?
Examples
Example 1:
Input: console.log(filteredArr)
Output: [1, 'a', 2, true]
Explanation: filter(Boolean) is shorthand for filter((x) => Boolean(x)), so every falsy value (0, false, '', null, undefined, NaN) is dropped.What is the result of arr.sort(), and why is it not numerically ordered?
Examples
Example 1:
Input: console.log(arr.sort())
Output: [15, 16, 18, 2, 23, 3, 4, 42]
Explanation: Default sort with no comparator converts each element to a string and sorts lexicographically by UTF-16 code units, so '15' precedes '2'.What does each call print? Walk through how copyWithin(target, start[, end]) mutates the array in place.
Examples
Example 1:
Input: arr.copyWithin(0, 3); arr.copyWithin(0, 4);
Output: ['b', 'a', 'r', 'b', 'a', 'r']; ['a', 'r', 'r', 'b', 'a', 'r']
Explanation: copyWithin overwrites starting at target by copying the slice from start, mutating in place so the second call operates on the result of the first.