1.

What is the issue with the code and how can it be fixed ?

Answer»

We will be implementing some, every and reduce by using of callbacks, in the same way, we used to implement forEach, map and filter in the previous question.

some

The Array prototype method some returns true if any element of the array fulfils the condition we are testing. Here also like filter, we will have the callback been CHECKED in an if statement in every iteration. This will test our condition and even if one of it pass we return a true and get out of LOOP. If the iteration is complete, it means not a single element satisfy condition and we return false.

every

It is the opposite of some. The method “every” will return true only if every element passes the test. Here we do a trick in the if statement. We check the opposite of the test, so say if element should be greater than 10, we are checking for less than 10. So, if even one is less than 10 we return false. And if we iterate through whole loop, means all element satisfy the condition so we return true.

 reduce

The method reduce is considered the hardest in the Array prototype methods to master. It is because it’s concept is quite different. It takes the whole array and iterate through it and returns a single value. It is useful to do sum/multiply/subtract of all the elements of an array, but is more powerful than that. To do this it have an accumulator, which is used to hold the number in each RUN. This accumulator will be operated with the current value of the iteration.
Now in our implementation, we first check whether an accumulator was supplied or ELSE make it to undefined. Now inside the loop we update the accumulator variable by using the callback.



Discussion

No Comment Found