-1

function x() {
  var a = 2;
  y();
}

function y() {
  a += 3;
}
x();
//returns a is not defined

If i declare a function (y) outside the function (x) where it's been called, why it isn't inherit the outer function's variables and values? There's a way to solve the problem described above?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

1 Answers1

1

Variable a is declared as part of the function x(). That's why a is available only inside x(). To solve the problem you have to pass variable a as the function parameter:

function x() {
  var a = 2;
  y(a);
}

function y(a) {
  a += 3;
  console.log(a);
}
x();
Mamun
  • 66,969
  • 9
  • 47
  • 59