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`.
Question Bank
Medium
JavaScript
6 questions
quiz
arrays
array-manipulation-patterns
interview-prep
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.var arr1 = 'john'.split('');
var arr2 = arr1.reverse();
console.log(arr1);
console.log(arr2);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.const arr = new Array('a', 'b', 'c', 'd', 'e');
arr[10] = 'f';
delete arr[10];
console.log(arr.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.const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2];
console.log(arr.indexOf(2));
console.log(arr.indexOf(4, 5));
console.log(arr.indexOf(2, 3));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.var arr = [1, 0, 'a', false, '', 2, true];
const filteredArr = arr.filter(Boolean);
console.log(filteredArr);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'.const arr = [2, 18, 3, 15, 4, 16, 23, 42];
console.log(arr.sort());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.const arr = ['f', 'o', 'o', 'b', 'a', 'r'];
console.log(arr.copyWithin(0, 3));
console.log(arr.copyWithin(0, 4));