Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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}`)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading