Debug fifteen programs that use array methods: SyntaxErrors in callbacks, TypeErrors from empty reduces, missing arrays, non-function callbacks, find results and Sets, and silent bugs from map(parseInt), forEach results, reduce without an initial value, truthy filter results and string comparators.
Question 11Medium
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
main.js
const qtyInputs = ["5", "12", "8"]; // values from form fields
const qtys = qtyInputs.map(parseInt);
console.log(qtys);
AparseInt cannot read form values
BThe array must be converted with Array.from
Cmap passes the index as parseInt's radix – use qtyInputs.map(Number) or (s) => parseInt(s, 10)
Dmap skips the first element
Correct Answer: Option C
parseInt("12", 1) and parseInt("8", 2) are NaN because 1 is an invalid radix and 8 is not a binary digit.
DWithout an initial value the first accumulator is the first order object, so + turns it into a string – pass 0 as the initial value
Correct Answer: Option D
The first call is { amount: 100 } + 200, which converts the object to "[object Object]" and concatenates from then on. reduce((sum, o) => sum + o.amount, 0) gives 600.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·