Search code examples
javascriptargumentsparameter-passingreturn-valuenested-function

Variable declared and assigned at global scope is undefined when called by a nested return function


When a function is created inside a function, the following code is returning a string with the name variable coming back as undefined. Since this is functionally scoped inside the global scope, I would have expected the name variable from the global scope to be found and used. Is the issue that parameter naming is not relevant for returned functions since these are only scoped inside the function?

My JavaScript code:

const name = "Ben"
function testReturn() {
  return function (name) {
    console.log(`Hello, ${name}`)
  }
}

And I called the function below:

> testReturn()()
Hello, undefined
undefined

Solution

  • The global constant name is shadowed by the local parameter name.

    Give one of them a different name or, if you aren't going to use it, remove the parameter entirely.

    const name = "Ben"
    function testReturn() {
      return function () {
        console.log(`Hello, ${name}`)
      }
    }