I have a question about this function:
function qwerty(n) {
return function(y) {
return y + 1
}
(++n) + n
}
console.log(qwerty(2));
The returned result is 7. Why? I don't quite understand it, it's supposed to return function(y).....
return the function with this statement, right? That is, everything after return should not be processed.
This is because with the return you are not returning a function but the result of the call to that function. The way in which the spaces are being put is somewhat strange (probably on purpose) and leads to confusion, which is why the result is not what would seem obvious.
Let's break down the code little by little. Originally the code is this:
But that's really equivalent to this with the line break removed:
That already gives an idea of where things are going. Let's move the function definition out and give it a name so it's not too confusing. And then the code is similar to this:
By doing (++n) you are adding 1 to n before calling the function , so it is like doing
suma1(3)
that it is going to return 4, and n is already valid,3
so the result is 7 (3+4). For clarity, this is equivalent to the initial code:This is known as closures , and you are declaring a function and executing it ( anonymous function ) returning the value of the anonymous function execution plus the value of n
Let's first make an example of an anonymous function and have it run!:
Once explained this; Let's pay attention to your code the following lines:
You are creating an anonymous function and executing it at the end with the parentheses () passing through parameters ++n , this way as it is first assigned and once assigned the anonymous function is executed and add the value of n (which you previously did ++n )
Let's execute the same code in the snippet changing n = 2
but what if we change the code to make it look a little better, the code you have is equivalent to:
The friend who gave you that code to start JavaScript... is not your friend
To understand how it works, we need to split the block like this, inside out:
It is the declaration of an anonymous function, which must be executed immediately after being declared. The way to execute an anonymous function is to pass the parameters in parentheses:
For example, the above call will return
2
.Next, we are using as a parameter the value ++n, which is an increment to the variable n before it is used. That is, it reads
suma 1 a n, y envíala como parámetro
. With this, the input value for the anonymous function is 3 when the parameter n is 2.Finally, we're adding the value of n to the result of the anonymous function, which, since we added 1 to its value via the incremental operator, now has a value of 3. Since the result of the function is 4,
4 + 3 = 7
.