0

Below is from a textbook that I am working through, but something doesn't make sense. Can someone please explain to me how I'm able to access the local variable "secret" from the global scope? When I run the code the output is '100'. I thought that variables declared inside of a function can't be accessed from outside the function. What is happening here that I can set "secret" to 100?

    var set, get;

    function val() {
        var secret = 0;

        set = function (arg) {
            if (typeof(arg) === "number") {
                secret = arg;   
            }
        };

        get = function () {
            return secret;
        };
    }

    secret = 100;

    document.write(secret);

output > 100


By the way, the textbook originally has the function as an immediate function. I changed to the above hoping that it would lead to a different outcome.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Ivan
  • 143
  • 2
  • 12
  • You may want to read this. http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – E_net4 Jan 06 '15 at 19:37

1 Answers1

0

You have a global and a local secret variable.

// Creating a global variable, not affecting the one inside val
secret = 100;
// This is accessing the global variable
document.write(secret);

If you actually run your val function, you'll see that they are different

 var set, get;

 function val() {
   var secret = 0;

   set = function(arg) {
     if (typeof(arg) === "number") {
       secret = arg;
     }
   };

   get = function() {
     return secret;
   };
 }

val();

secret = 100;
document.write("global secret = " + secret + '<br />');
set(5);
document.write("private secret = " + get() + '<br />');
document.write("global secret unaffected = " + secret + '<br />');
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217