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.