Skip to content
Advertisement

Functions and parenthesis in Javascript

I don’t understand how all those f() function work, can someone explain why it prints two ‘1’, I know it prints ‘1’ for every ‘()’ after f(f), but I don’t know why.

JavaScript

And why does the ‘i’ doesn’t increase?

Thank you.

Advertisement

Answer

JavaScript

is equivalent to

JavaScript

is equivalent to

JavaScript

If you did call each of t1 or t2 multiple times instead of just once, you’d increment the i from the respective closure some more. But if you instead just chain them, they call f again and initialise a new var i = 0 for a different closure.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement