Difference when returning the value?

-1

What is the difference between doing:

function b() {
 return function(){return b();}
}

versus:

function b() {
 return b();
}

Is it the same or does it have advantages? I've seen it in many recursive functions.

    
asked by Eduardo Sebastian 10.11.2017 в 23:02
source

2 answers

1

As I told you in my comment, the second code does not make much sense. b() would call itself to complete the browser's stack or exploit your computer, whichever comes first.

The first code, although it does not make sense in your example, is a structure associated with functional programming.

Instead of a function that adds two numbers:

function suma(a, b) {
  return a+b;
}

You can make a function that returns another function , which will behave according to how you generated it. For example, look at the following function

function sumarle (a) {
  return function(b) { return a+b;  };
}

Then you can say "I want a function that adds 2 to anything that happens to me". You generate it like

var sumarle2 = sumarle(2);

And another that adds 5 to everything you spend

var sumarle5 = sumarle(5);

Obviously you could also use them directly without declaring them as variables:

   console.log(sumarle(2)(19)); // retorna 21

To try:

function sumarle (a) {
      return function(b) { return a+b;  };
    }

    var sumarle2 = sumarle(2);
    var sumarle5 = sumarle(5);

    console.log(sumarle2(7)); // retorna 9
    console.log(sumarle5(10)); // retorna 15
    
    console.log(sumarle(2)(19)); // retorna 21

In the end, the idea is that through games like this you can make composition of functions. Instead of writing yourself two functions to add 2 + x and 5 + x, you got them from a "function factory".

If you get creative, you could do a sum function that returns the sum when it receives two parameters, or returns a function when it only receives one, which would be currify the sum

If you notice the functional programming, yesterday I read an article very well explained:

link

    
answered by 10.11.2017 / 23:17
source
0

Basically it's the same code written in two different ways, that's the closest thing to a recursive function. A recursive function would be like this:

function factorial(num)
{
    if (num < 0) {
        return -1;
    }
    else if (num == 0) {
        return 1;
    }
     return (num * factorial(num - 1));
}

var resultado = factorial(8);
document.write(resultado);

// Salida: 40320

An example of how to calculate the factorial of a number, but if you call the function itself, an infinite loop will be created again until your PC crashes.

    
answered by 11.11.2017 в 00:20