Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript Need help with JavaScripts reduce() function

Hey!

I'm learning JS by myself, and I've found a piece of code i'm not able to understand [may seem easy for you, but i'm a beginner 🙂]

Why does the following code display '0' in the console?

JavaScript:
const sum = (...args) => {
    return args.reduce((a, b) => a + b, 0);
}

console.log(sum());

Thx for your help!!
 
I'm not really familiar with javascript but,
You did not enter any values in the function call
0 may be the default value set to return


JavaScript:
const sum = (...args) => {
    return args.reduce((a, b) => a + b, 0);
}

console.log(sum(5,5));

Code:
#output
10
 
@menator01 is exactly correct. There were no arguments passed and the starting value is zero.
The args variable is passed and set as an array by the spread operator.
reduce can take the two parameters a being the element of the array as it loops through it and b being the value stored in memory, which is defined with a starting value of zero.
so imagine reduce loops through the elements represented by a and adds b to it, which is stored in memory
[1,2,3] would be processed as the following:

1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
That's a messy explanation but I hope that made sense.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom