2

The parameter or argument in the function square (I don't know which one is correct) is "y" but in the for loop it is "x". Why does the program have to do a copy of "x" and call it "y"? It works fine with "x" too (I tried) and the code works fine. So why the extra trouble? It just makes more sense to me since I'm new at JS to keep the names the same. Can someone explain?

document.writeln("<h1>Square the numbers from 1 to 10</h1>");

for (var x = 1; x <= 10; ++x)
  document.writeln("<p>The square of " + x + " is " + square(x) +
    "</p>");

function square(y) {
  return y * y;
} //end


//This works too:
// function square(x) {
//
//    return x * x;
//  }
Boann
  • 48,794
  • 16
  • 117
  • 146
  • 1
    You can name them however you want. Name them so they make sense in their limited context. This is precisely so you can use local variable names freely, and aren’t stuck with using the same names all throughout your app. – deceze Aug 22 '19 at 18:45
  • https://www.w3schools.com/js/js_scope.asp – Alexandr Maliovaniy Aug 22 '19 at 18:47
  • This code is from a book internet-and-world-wide-web-how-to-program-5th-edition. I'm afraid there's more to it but at the same time what you say sounds right. Don't know why the book wrote the code like that. Thank you for your answer! – Anna Bergman Aug 22 '19 at 18:50
  • You might want to consider reading http://eloquentjavascript.net/03_functions.html – Bergi Aug 22 '19 at 21:47

2 Answers2

1
function square(y){ // whatever parameter name

            return y * y;

        }

Above one is a function definition and it is a individual thing that can invoke from anywhere in the program. As it might be use in multiple places, any parameter name can use.

whenever you are invoking a function, you should have more concern about the value that are passing to the function.

Make sure you are using the same parameter name in the function definition.

lets say the above program have more than 1 for loop,

     for ( var x = 1; x <= 10; ++x )
            document.writeln( "<p>The square of " + x + " is " + square(x)
            + "</p>" );

     for ( var y = 1; y <= 5; ++y )
            document.writeln( "<p>The square of " + y + " is " + square(y)
            + "</p>" );


function square(z){ 
            return z * z;
        }
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
  • 1
    Ahhh, NOW it makes sense to me! :D Thank you!! – Anna Bergman Aug 22 '19 at 19:07
  • happy to hear.. if it helps, could you please accept it as answer? – Sarun UK Aug 22 '19 at 19:08
  • If you want to improve JS knowledge, suggesting to read JavaScript: The Good Parts by Douglas Crockford –  Aug 22 '19 at 19:16
  • Also consider some other calls like `square(5)` or `square(a + b)` or `square(+prompt() + 3)`. You wouldn't have any variable name on the outside. What gets passed into the function is only a value. – Bergi Aug 22 '19 at 21:45
1

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.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • "*In JavaScript scopes are defined by their enclosed "Execution Contexts"*" - no. JS has lexical scope, it is not affected by the call stack at all. – Bergi Aug 22 '19 at 21:42
  • @Bergi - No. "When control is transferred to ECMAScript executable code, control is entering an execution context. Active execution contexts logically form a stack." Execution contexts contain lexical environments. "A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment". – Travis J Aug 22 '19 at 22:15
  • Yes, surely the topmost execution context determines the active scope. But those scopes are not defined by the call stack, they are defined by the code structure. – Bergi Aug 22 '19 at 22:23
  • @Bergi - The topmost, as in deepest execution context would be the active scope, having its own lexical environment. It would have a reference to the parent context where another lexical environment would also exist. And so on, and so forth. Those execution contexts are created based on which code is currently being executed (known generally as the point where control currently is), there can be many contexts in the stack, as defined by the path of execution. Calling a function creates an execution context, so you are factually wrong in stating that the scope isn't determined by the calls. – Travis J Aug 22 '19 at 23:29
  • @Bergi - "Every invocation of an ECMAScript code function (13.2.1) also establishes and enters a new execution context, even if a function is calling itself recursively. When control enters an execution context, the execution context’s ThisBinding is set, its VariableEnvironment and initial LexicalEnvironment are defined, and declaration binding instantiation (10.5) is performed." -http://www.ecma-international.org/ecma-262/5.1/#sec-10.4 – Travis J Aug 22 '19 at 23:37
  • @Bergi - Respectfully, but really, you are just going to confuse future visitors by defending your false accusation. JavaScript scopes are defined by their enclosed "Execution Contexts" is entirely accurate. Please remove your downvote and your comments. – Travis J Aug 22 '19 at 23:38
  • No, I stand by my point that the term "defined by" is misleading, and I consider the mention of execution contexts to be not helpful (if not outright confusing) for answering the OPs question. Also, your last paragraph is plain wrong. – Bergi Aug 22 '19 at 23:51
  • It is a little bit confusing to see you triple down when clearly wrong. Not only is this the exact phrasing ECMA uses, it is factually 100% correct in use here. I would appreciate that you stop simply stating "no" or "wrong" without any sort of explanation, as you are clearly walking back these statements when pressed. You may stand by your point, but, just to be clear, you are fully wrong here. – Travis J Aug 23 '19 at 05:50
  • You are citing an outdated spec. If we look at [the current one](http://www.ecma-international.org/ecma-262/#sec-executable-code-and-execution-contexts), the important section there is "*Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.*" Those are the things that define a scope, and it doesn't talk of execution contexts at all. – Bergi Aug 23 '19 at 08:41
  • Sure a lexical environment also gets created alongside an execution context when a function is called, but this is not the only way. And one doesn't need to talk of execution contexts at all to answer the question, just saying "a scope (that holds local variables) is created when a function is called" would suffice. – Bergi Aug 23 '19 at 08:44
  • Regarding your final paragraph, we use scoping mechanisms to be able to use the same identifier to refer to different local (and, sometimes, temporary) variables, instead of each identifier being global. This facilitates encapsulation, modularity and reusability of code. We do *not* use scopes to help garbage collections or to make lookup faster. (Heck, if we didn't use scopes, we wouldn't even need to use lookups - apart from the parsing stage -, as every variable location would be static!) – Bergi Aug 23 '19 at 08:51
  • @Bergi - Alright buddy, I do appreciate the engagement, but at least take me to dinner first! The spec I cite overall may have parts which are outdated, but the structure of the execution context is not one of them. The current spec you cite shows the same exact structure of composition with relation to context and scope. *Every* scope is contained in an execution context. It may be a single level deep in edge cases. It is also not the *only* way, but it is the *vast* majority of the situations and as such it defines it in the sense that it embodies it. – Travis J Aug 23 '19 at 19:50
  • @Bergi - Scoping mechanisms are quintessential to garbage collection. They create all sorts of allowances for the interpreter engines to introduce efficiency. You even state "we wouldn't need lookups" if that were the case, but the reality is we do badly need them, and they facilitate all the nice features introduced in the newest version of ECMA as well, such as async and yield functionality. – Travis J Aug 23 '19 at 19:53
  • Re "*Every scope is contained in an execution context*": many of them are contained in closure objects. (And there's also the global scope which exists outside of any execution, but let's disregard that. Re "*Scoping mechanisms are quintessential to GC and allow for interpreter efficiency*", in my book scoping mechanisms were introduced to allow the programmer to argue locally about code - that they also allow the compiler to do the same is just a nice byproduct. – Bergi Aug 23 '19 at 21:59
  • Your phrasing seems to be self referencing. This is the problem when you start citing your own writing as source material. The whole reason for citing official documentation such as the ECMA source is to make sure we all use the same verbage, instead of just personal jargon. There are closures, but no closure objects. In fact, closures are backed by execution contexts. As well, literally all scope is contained in an execution context, including the "global scope" which is the originating execution context for the script execution. Scopes were not introduced solely for pedantic reasons. – Travis J Aug 24 '19 at 20:25
  • If you need the spec terms, I am referring to the *[[Environment]]* internal slot of [function objects](http://www.ecma-international.org/ecma-262/#table-27), which we colloquially call [closures](https://en.wikipedia.org/wiki/Closure_(computer_programming)) although the spec doesn't define that term. – Bergi Aug 24 '19 at 21:57