-2

I am pretty new in JavaScript and I have some doubts related to the variable scope.

So I tryed to do this example:

function outer() {

    alert("INTO outer()");
    var val1 = 1;

    inner();

    alert(val2);
}

function inner() {
    alert("INTO inner()");

    val2 = 2;


}

outer();

In this simple example the outer() function is perform, in this function I call the inner() function that declare and initializes the val2 variable. Then come back to the outer() function and from here I access and print the val2 value.

So it seam to me that in Javascript I can access to the variable defined in the inner function from the outer function but I can't access to the variable declared in the outer function from the inner function.

Is it true? If it is true why this choose?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

2 Answers2

3

It is true..The use of var in function 'outer' makes val1 local variable whereas val2 of function 'inner' has global scope since the keyword var is not used.

Sanjay Maharjan
  • 359
  • 1
  • 12
2

The declaration in your "inner" function is missing the var keyword. That makes val2 a global symbol.

Pointy
  • 405,095
  • 59
  • 585
  • 614