Ad
  • Custom User Avatar
  • Custom User Avatar

    Yes.

    The higher-level methods (especially those for iteration) are indeed slower than their low-level counterparts. However, Array#reduce is still a native method that is optimized at the C-level. The difference in speed in most practical scenarios is negligible, the difference in elegance is not.

    Writing "good" code is about readability and expressiveness just as much as it is performance (not to say that this solution is the most of either). JavaScript gives us the syntactic sugar to make this possible. To ignore this in favor of more primitive concepts is a waste.

    Which would you rather read?

    arr.reduce((sum, item) => sum + item, 0);
    

    vs.

    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
    	sum += arr[i];
    }
    

    If you start arguing about the relative speed of every single statement, you're going to waste a lot of time prematurely optimizing the readability out of your code.

  • Custom User Avatar

    You could also try the filter method or recursion to solve this :)

  • Custom User Avatar

    It's also good to expand on your knowledge and practice all methods of solving as well, regex being one of them even if they are slower :)