Javascript - Function Scope
Code Life
By Pierre Marsaa
Every Call Starts Fresh
Suppose you write a fight() function with a local variable let turns = 0 inside it to count how many turns have passed.
If you call fight() three times in a row, you might expect turns to reach 3—but look at what actually happens:
↗️
Loading editor...
↶
↷
It prints 1 every single time! That's because every function call creates a brand-new set of local variables, runs the code, and destroys those local variables as soon as the function finishes. Nothing inside a normal function call is kept for the next call.
Verify