0

I have a function named 'parent' which has a nested function 'child' in it. Both have variables named 'total' in it. I want to access parent's 'total' inside child's total. How can I do that. I've read about closures but it doesn't answer my question.

function parent() {
  var total = 20; 

  function child() {
    var total = 30;
    console.log(total); //output: 30
    //I want to access parent's total variable here
    console.log(total); //expected output: 20
  }
}
  • This is called [variable shadowing](https://stackoverflow.com/questions/11901427/an-example-of-variable-shadowing-in-javascript) and there is no way to access the parent's `total`from within `child` when shadowed like that – mhodges Apr 04 '18 at 16:29
  • use a different name – Joe Warner Apr 04 '18 at 16:30
  • It was a random thought that popped up in my mind. I searched a lot but could not figure out a way, thus ended up asking it here. Thank you all. – Abhinav Preetu Apr 05 '18 at 04:30

1 Answers1

1

You can't. As others mentioned, this is called variable shadowing. It completely masks the variables from the outer contexts.

The easiest way to get around this would just be to simply name them differently. It should generally not be too destructive to give the child a different variable name:

function parent() {
  const total = 30;
  
  function child() {
    const childTotal = 20;
    
    console.log(childTotal);
    console.log(total);
  }
  
  child();
}

parent();

Another alternative would be to pass the parent value in as an argument to the child, and in the parameters, give it a different name there:

function parent() {
  const total = 30;
  
  function child(parentTotal) {
    const total = 20;
    
    console.log(total);
    console.log(parentTotal);
  }
  
  child(total);
}

parent();

Finally, if the value was equivalent to a public static value, you could grab it that way:

function parent() {
  function child() {
    const total = 20;
    console.log(total);
    console.log(parent.total);
  }
  
  child();
}

parent.total = 30;

parent();

That about sums up all of your options. As said earlier, just changing one of the names is by far the best solution for 99% of the cases.

samanime
  • 25,408
  • 15
  • 90
  • 139