JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – can reduceRight method really sum an array elements

JavaScript Quiz – can reduceRight method really sum an array elements

Array reduceRight Method –

Javascript array reduceRight method is also used to reduce an array to a single value like array reduce method but it iterate from right to left.

The reduceRight() method takes two arguments a reducer callback function and an optional initial value.

It’s syntax looks like –

array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)

For more detail about javascript array reduceRight method click here.

JavaScript Question

In this javascript quiz code, let’s find out can array reduceRight method really sum an array elements as it also works same as array reduce.

First, we declare a variable array using the let keyword in which we assign a javascript array which contains only a number elements.

let array = [1, 2, 3, 4, 5];

In the second step, create another variable sum using let in which result of reduceRight store.

let sum = array.reduceRight((total, current)=> { … });

Inside the reduceRight, we are adding a total with the current value and at the initial parameter, we define a blank string.

return total + current;

Finally, we are checking the output of sum variable, any idea what should be the output?

Answer – 54321

Click To Run Code

Explanation

So, you know the answer is “54321”. But why, we are adding all the elements. It’s should give us 15 answers. Let me explain.

We already know what happen when we add string with number, instead of addition it get concatenated.

But now you are thinking that every element in array is number. Yes, it’s true but remember the value of total as it’s initial value is empty string .

At last, That’s why we get an answer “54321“.

Let me know in the comment section, how you fix this.

I hope you understand the concept and logic behind it.

But wait, i have something more for you –

Check out our other javascript quiz – 

  1. JS Quiz – var in a block scope work
  2. JavaScript Quiz – string split method really a case sensitive
  3. JS Quiz – does typeof of Symbol really give a string
  4. JavaScript Quiz – can setTimeout in the for loop print values

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link