+ 5

Can someone explain this code, please?

function abc (a) { return (function(y){ return(y+1);}) (++a)+a+a; } alert(abc(2))

27th May 2017, 11:51 AM
Anton Rochniak
Anton Rochniak - avatar
10 Answers
+ 13
function abc (a) { return (function(y){ return( y+1 ); } ) // y is 2, so... y + 1 = 3 ( ++a ) +a +a; // ++a = 4 + a + a ===> 4 + 3 + 3 // ++a = 4 because "a" is now 3, like "y" } alert(abc(2)) // I found this solution and it works, but i'll wait an expert opinion about it.
27th May 2017, 12:10 PM
Maz
Maz - avatar
+ 10
Because you passed 2 as argument in the call of abc( ) function. alert( abc(2) )
27th May 2017, 12:14 PM
Maz
Maz - avatar
+ 8
something interesting happens here you return the calling of a function 1) 2 is passed to abc 2) returning function(...){function body}(...) calls it 3) passing ++a increments a, passing the value 3 4) the inner function returns 3+1 (4) 5) return 4+a+a 6) what is the value of a after ++a? 7) that's right! 3 8) return 4+3+3 9) ???? 10) profit!!!!
27th May 2017, 12:18 PM
Burey
Burey - avatar
+ 8
Ahhhhhhh @Burey what a whole world explaination
27th May 2017, 12:21 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 7
.... it is quiet advance javascript This trick can explain how the whole jQuery work.... What did I say? Well....This code is like as... function abc (a) { return (function(y){ return( y+1 ); } )(a++)+a+a } alert(abc(2)) Try (function(a){document.write(a)})(1) That will print 1 to screen... Now try the other one var a = function(i){document.write(i)}; a(); "if () along the function.that function will be executed" That is how setInterval(function(){},0) work
27th May 2017, 12:17 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 7
hehe....kinda hard to explain it.....
27th May 2017, 12:29 PM
Burey
Burey - avatar
+ 5
A breakdown with pretty printing. I understand if my way doesn't help, but worth a try. https://code.sololearn.com/WxTEI1rejx0I/?ref=app
29th May 2017, 4:11 AM
Kirk Schafer
Kirk Schafer - avatar
+ 5
It was very hard to understand this code, but i finnally made it!) And now it looks simple...😊 One more time thanks to everyone!
29th May 2017, 12:46 PM
Anton Rochniak
Anton Rochniak - avatar
+ 3
Thank's for everyone! I will try to understand what you write, because I also have some problems with english))
27th May 2017, 12:24 PM
Anton Rochniak
Anton Rochniak - avatar
+ 2
I think like you too. But i don't understand why y = 2?
27th May 2017, 12:13 PM
Anton Rochniak
Anton Rochniak - avatar