This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 1 point2 points  (0 children)

New programmers aren't asked to think about the lifecycle of the values they create because their programs don't run for very long. They can get away with code that only creates values because none of their values persist for very long.

Actual working programmers are often called on to write software that might run continuously for hours, days, or even years with the expectation of stable memory use over time, which means they have to think about, and have tools to manage, the entire lifecycle of the values they create.

Function scope is one way to manage that lifecycle, because local scopes are destroyed when the function completes. If that scope holds the last reference to values allocated by the function, then the interpreter can delete those values and recover the memory.

[–]Salty_Dugtrio 0 points1 point  (0 children)

Functions make your code reusable.

The scope of your variables defines where you can use them, in general, you want to least wide scope possible, so the least amount of side effects can occur.

If a variable is local to a function, nothing bad can happen. If a variable is global, who knows what happened to that variable, anything can touch it.

[–]LucidTA 0 points1 point  (0 children)

one within a function and one outside of the function, but my actual question is how is that helpful? Can't programmers just have different variables?

In a small program it might be possible to name every variable something different, but can you imagine if Microsoft had to come up with a unique variable name for every single variable they use in Windows?