This is the result of what is known as "scope" in Computer Science.
In JavaScript scopes are defined by their enclosed "Execution Contexts" ECMA, which was designed similarly to a stack of cards.
Practically speaking, this means there are areas where names reference memory locations. Your coding example highlights a scenario where two different memory locations are referenced using the same name because they are in different areas.
In JavaScript, one way to create one of these areas for different name references is to use a function. Inside of the function, new names will take precedence over outside names.
So, when you have a situation such as:
for ( var x = 1; x <= 10; ++x ){
square(x);
}
function square(x){
return x * x;
}
The confusing part here is mostly that the same name for the variable was used in both places.
The x variable inside of the function is actually in its own name reference area. Inside of that area, x now refers only to the parameter value of x, and not to any other value.
From a more technical angle, there is an execution context currently executing the code inside of the for loop. It contains a memory environment which has an entry for x. When square(x)
is called, it uses that value to pass to a new execution context for the function square. Inside of the execution context for square, there is also a memory environment. This memory environment contains an entry for the function's parameter, also named x. Note that the memory location is different since there are two different execution contexts, and two different memory environments.
So really, there doesn't need to be different names from a technical perspective. However, from a readability perspective it is hard to read and that makes the program harder to build later on.
As far as why this is done, it is because of memory management and execution efficiency. There is a mechanism called "garbage collection" which runs when it can (when there is free processor time) that will remove unused memory. This memory is determined to be unused when it goes out of scope (which is why the execution contexts are important). In addition, during lookup for variable values, having a small area to start with and then expanding out makes the lookup much faster. These are the two main reasons why scoping is used behind the scenes.