JavaScript Array Methods 2 — Questions and Answers
Question 1: What does `Array.prototype.forEach()` return?
- A new array of the results
- The original array
- undefined (Correct answer)
- The number of elements processed
Correct answer: undefined
`forEach()` always returns `undefined`. It is used purely for side effects (like logging or mutating external state), not for transforming data. Use `map()` if you need a new array.
`forEach()` calls the callback for each element but discards the return values. Returning a value from the callback has no effect. Unlike `map()`, `filter()`, or `reduce()`, `forEach()` cannot be chained because it returns `undefined`. Also note: you cannot break out of a `forEach()` loop (use a regular `for` loop or `some()`/`every()` with a flag instead).
Question 2: What does `Array.from()` do?
- Creates an array from a range of numbers
- Creates a new array from an array-like or iterable object (Correct answer)
- Converts an array to a string
- Merges multiple arrays
Correct answer: Creates a new array from an array-like or iterable object
`Array.from()` creates a new shallow-copied Array from an array-like (has `length` and indexed elements) or iterable object (like `Set`, `Map`, `NodeList`, `String`).
`Array.from('hello')` → `['h','e','l','l','o']`. `Array.from(new Set([1,2,2,3]))` → `[1,2,3]`. `Array.from({length: 3}, (_, i) => i)` → `[0,1,2]`. The second argument is a map function applied to each element during creation. It's the standard way to convert DOM NodeLists to arrays to use array methods on them.
Question 3: What is the result of `[1,2,3].indexOf(4)`?
- null
- undefined
- -1 (Correct answer)
- false
Correct answer: -1
`indexOf()` returns the first index at which a given element is found. If the element is not found, it returns `-1`. This is the conventional JavaScript way to indicate 'not found'.
`indexOf()` uses strict equality (`===`) to find elements. For checking existence (not position), `includes()` is more readable (`[1,2,3].includes(4)` → `false`). `indexOf()` does not work well for finding objects or NaN (use `findIndex()` for complex comparisons). `lastIndexOf()` searches from the end.
Question 4: What does `Array.prototype.every()` do?
- Runs the callback for every element and returns an array
- Returns true only if the callback returns truthy for ALL elements (Correct answer)
- Returns the last element that passes the test
- Creates a copy of the array
Correct answer: Returns true only if the callback returns truthy for ALL elements
`every()` tests whether all elements in the array pass the test implemented by the provided function. It returns `true` only if the callback returns truthy for every element, otherwise returns `false`.
`every()` short-circuits on the first falsy result — it doesn't test remaining elements. For an empty array, `every()` returns `true` (vacuously true). This is the complement of `some()`: `arr.every(fn)` is equivalent to `!arr.some(el => !fn(el))`. Common use: validating that all form fields are filled, all numbers are positive, etc.
Question 5: What is the difference between `Array.prototype.push()` and `Array.prototype.concat()`?
- Both modify the original array
- `push()` modifies the original array; `concat()` returns a new array (Correct answer)
- `concat()` modifies the original; `push()` returns a new array
- They are identical for adding a single element
Correct answer: `push()` modifies the original array; `concat()` returns a new array
`push()` adds elements to the end of the original array (mutates it) and returns the new length. `concat()` returns a new array by merging arrays/values without modifying the originals.
`arr.push(4)` modifies `arr` and returns the new length. `arr.concat([4])` returns `[...arr, 4]` as a new array, `arr` unchanged. For spreading arrays into a new one, the spread operator is modern: `[...arr1, ...arr2]` (equivalent to `concat`). For functional programming, prefer `concat` or spread to keep data immutable.
Question 6: What does `Array.prototype.sort()` do by default?
- Sorts numbers in ascending order
- Sorts elements as strings in ascending Unicode order (Correct answer)
- Sorts elements in insertion order
- Returns a sorted copy, not modifying the original
Correct answer: Sorts elements as strings in ascending Unicode order
By default, `sort()` converts elements to strings and sorts by Unicode code points in ascending order. This means `[10, 9, 2].sort()` returns `[10, 2, 9]` (lexicographic, not numeric). Always provide a comparator for non-string sorting.
Default sort: `[10, 9, 2].sort()` → `[10, 2, 9]` because '1' < '2' < '9' alphabetically. For numeric sort: `arr.sort((a, b) => a - b)` (ascending) or `arr.sort((a, b) => b - a)` (descending). `sort()` modifies the original array in place. In modern engines (V8 from Node 11+), `sort()` is stable (preserving order of equal elements).
What does `Array.prototype.forEach()` return?