0
How to solve this challenge
I don't understand how this code works and why it alerts 7. Give me some light, please! function abc(a) { return(function(y) { return y + 1; }) (++a) + a; } alert(abc(2));
2 Answers
+ 3
proper indentation/spacing should help to understand:
function abc(a) {
return (function(y) {
return y + 1;
})(++a) + a;
}
alert(abc(2));
alert is called with the return value of abc call with argument == 2
abc function get 2 as value of its ''a' argument, and return an IIFE (Immeddiatly Invoked Function Execution -- a function called only once at creation time) wich get ++a (pre-increment of 'a', so 2+1 = 3) as its 'y' argument added to 'a' wich is now 3.
return value of the IIFE is y+1 = 3+1 = 4
so return value of abc is 4+3 = 7
so 7 is passed to alert ^^
+ 3
abc(2) // value of a==2
Here abc function is returning a self invoking function with ++a==3 value.
Self invoking function returns 3+1 ==4
So final value is 4+a==4+3==7