What is the advantage of using a function over loops?

前端 未结 3 1403
南旧
南旧 2021-01-26 07:52

It seems that functional iterators are replacing the use of for loops in JS.

What is the advantage of passing a function such as map or reduce

3条回答
  •  天涯浪人
    2021-01-26 08:19

    good answers here already. will just add one thing i came to appreciate with time: when you do things the "imperative"/old way it tends to encourage a style of programming with a lot of intermediate variables, mutable things all over and also the "while i'm iterating i might as well do this other thing on the same data" which is the biggest trap in code design - sacrificing separation of concerns for dubious performance gains. Consider this example

    const numbers = [1,4,9,16];
    let sum = 0;
    let onlyEvenNumbers = [];
    for(i = 0; i < numbers.length; i++) {
      sum += numbers[i];
      if(numbers[i] % 2 == 0) {
        onlyEvenNumbers.push(numbers[i]);
      }
    }
    

    this is bad imo cause you're gaining very little (if any) performance and the for loop doesn't have a clear single purpose. of course in this simple case it's probably ok, but it can get real ugly real fast. also it's not clear at first glance what gets stored in the onlyEvenNumbers var until you read to the bottom of the for loop - again, probably ok here, but if the for loop gets big it may get confusing. functional approach for the win (also notice things can be not only const, but are even not mutated once constructed):

    const numbers = [1,4,9,16];
    const sum = numbers.reduce((acc, val) => acc + val);
    const onlyEvenNumbers = numbers.filter(num => num % 2 == 0);
    

提交回复
热议问题