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
  }
}
3
  • This is called variable shadowing and there is no way to access the parent's totalfrom within child when shadowed like that Commented Apr 4, 2018 at 16:29
  • use a different name Commented Apr 4, 2018 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. Commented Apr 5, 2018 at 4:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.