marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.03k stars 799 forks source link

Unclear section on parameter scope #273

Closed clmay closed 6 years ago

clmay commented 6 years ago

Hey Marijn,

Huge fan of EJS - have the 2nd edition in print and have been going through the 3rd edition draft online as well.

I think the example given in the Chapter 3 section on parameter scope is a little unclear.

const halve = function(n) {
  return n / 2;
};

let n = 10;
console.log(halve(n * 2));
// → 10

The goal of the section is to clarify that if the same variable name is used both outside a function and also within it, only the innermost scope is used and the function will not recognize the variable as declared without. While the code example obviously demonstrates it, I think it is a little unclear because the result of calling halve(n) with n as the function parameter happens to give the same result we would expect if the function were accessing the variable from the global scope...

Perhaps an example like the following would better demonstrate the point?


let x = 2;
let y = 10;

const fraction = function(x, y) {
  let numerator = x; // this reads the *parameters* x and y passed to the function,
  let denominator = y; // not the globally-defined variables outside the function body
  return numerator / denominator;
}

console.log(fraction(3, 10));
// → 0.3 (not 0.2)
marijnh commented 6 years ago

Attached patch changes the example so that the number 10 doesn't occur twice, which indeed makes it easier to tell the variables/values apart.