0
function parent() {
    let name = 'joe';
    printName();

    function printName() {console.log(name)}
}

this works, but i want to move printName outside of the other function.

function parent() {
    let name = 'joe';
    printName();
}
function printName() {console.log(name)}

but this does not work, since name is stuck inside the parent function. Is there a way to send the current scope of parent to printName when I call that function on line 3? something like .bind but for all variables not just this

stackers
  • 2,701
  • 4
  • 34
  • 66
  • 3
    No, it's not possible. Make `name` a parameter to the function. – Barmar Dec 06 '22 at 17:46
  • 1
    You may want to look into [Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) as a possible alternative. – PM 77-1 Dec 06 '22 at 17:50

1 Answers1

1

Is there a way to send the current scope of parent to printName when I call that function on line 3? something like .bind but for all variables not just this

No. But here are two alternatives:

  1. Use functional programming techniques: create a name parameter for the printName function and provide the name argument when invoking it:

function printName (name) {
  console.log(name);
}

function parent () {
  let name = 'joe';
  printName(name);
}

parent(); // logs "joe"
  1. Initialize an object that is in scope for both functions and mutate its properties. In this second approach, both functions are closures because they depend on the reference to obj being available when they are invoked:

const obj = {};

function printName () {
  console.log(obj.name);
}

function parent () {
  obj.name = 'joe';
  printName();
}

parent(); // logs "joe"

The second approach is conceptually like assigning properties to the global object, but it avoids global scope pollution.

jsejcksn
  • 27,667
  • 4
  • 38
  • 62