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)
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.
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)
withn
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?