javascript – Why does this function return this result?

Question:

``````function qwerty(n) {
return function(y) {
return y + 1
}
(++n) + n
}

console.log(qwerty(2));``````

The returned result is 7. Why? I do not quite understand, it is assumed that with this statement `return function(y).....` return the function, 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.

We are going to decompose the code little by little. Originally the code is this:

``````function qwerty(n) {
return function(y) {
return y + 1
}
(++n) + n
}

console.log(qwerty(2));``````

But that's really equivalent to this by removing the line break:

``````function qwerty(n) {
return function(y) {
return y + 1;
}(++n) + n;
}

console.log(qwerty(2));``````

That already gives an idea of ​​where things are going. Let's move the definition of the function out and give it a name so it's not so confusing. And then the code is similar to this:

``````function suma1(y) {
return y + 1;
}

function qwerty(n) {
return suma1(++n) + n;
}

console.log(qwerty(2));``````

By doing (++ n) you are adding 1 to n before calling the function , so it is like doing `suma1(3)` which will return 4, and n is already worth `3` so the result is 7 (3 + 4 ). To be clearer, this is equivalent to the initial code:

``````function suma1(y) {
return y + 1;
}

function qwerty(n) {
n = n + 1;
return suma1(n) + n;
}

console.log(qwerty(2));
``````
Scroll to Top