Deal of The Day! Hurry Up, Grab the Special Discount - Save 25% - Ends In 00:00:00 Coupon code: SAVE25
Welcome to Pass4Success

- Free Preparation Discussions

Salesforce JS-Dev-101 Exam - Topic 7 Question 9 Discussion

Refer to the code below:01 const myFunction = arr => {02 return arr.reduce((result, current) => {03 return result + current;04 }, 10);05 }What is the output of this function when called with an empty array?
D) Returns 5 (Text here appears to be a typo; correct value is 10, see explanation.)
A) Returns 0
B) Throws an error
C) Returns NaN

Salesforce JS-Dev-101 Exam - Topic 7 Question 9 Discussion

Actual exam question for Salesforce's JS-Dev-101 exam
Question #: 9
Topic #: 7
[All JS-Dev-101 Questions]

Refer to the code below:

01 const myFunction = arr => {

02 return arr.reduce((result, current) => {

03 return result + current;

04 }, 10);

05 }

What is the output of this function when called with an empty array?

Show Suggested Answer Hide Answer
Suggested Answer: D

We call:

myFunction([]);

Inside:

arr.reduce((result, current) => {

return result + current;

}, 10);

Key points about Array.prototype.reduce:

Signature: array.reduce(callback, initialValue)

If initialValue is provided and the array is empty, reduce:

Does not call the callback at all.

Simply returns initialValue.

Here:

arr is [] (empty).

initialValue is 10.

So:

No iterations of the callback happen (no elements to process).

The return value is the initial value: 10.

So the actual output is:

myFunction([]) === 10;

Among the options:

A: 0 -- incorrect, because the initial value is 10, not 0.

B: Throws an error -- reduce throws only if the array is empty and there is no initialValue. Here we have an initial value, so no error.

C: NaN -- there is no arithmetic with undefined or invalid values; we just return 10.

D: Returns 5 -- the numeric value given is wrong; the correct value is 10.

Given the logic, the correct conceptual result is 10. The option text ''Returns 5'' is almost certainly a typo for ''Returns 10''. Since the letter that is intended to represent the correct behavior is D, we keep:

Answe r: D

Study Guide / Concept Reference (no links):

Array.prototype.reduce behavior with initialValue

Behavior of reduce on an empty array with and without initialValue

Return value when no iterations run


Contribute your Thoughts:

0/2000 characters

Currently there are no comments in this discussion, be the first to comment!


Save Cancel