Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parameters and scopes

Slightly confused by this Eloquent Javascript explanation of parameters and scopes.

It states that variables declared outside of a function are global, that variables declared inside a function are local, and that variables declared inside a function without a preceding var are essentially referencing a similarly named global variable. Fine. That makes sense. But then this code throws me for a loop.

var x = "outside";

var f1 = function() {
  var x = "inside f1";
};
f1();
console.log(x);
// → outside

var f2 = function() {
  x = "inside f2";
};
f2();
console.log(x);
// → inside f2

Logging out the value of x in the first function should result in "inside f1" because that variable was declared locally. And that second function (being that it contains a variable declared without var and thus references the global one declared up at the very top) should result in "outside." But...it doesn't in either case.

I get the gist of what's supposed to happen. But unless I'm reading incorrectly, it seems as if it's the opposite of what the author describes. This can't be a typo.

like image 290
calyxofheld Avatar asked May 15 '26 17:05

calyxofheld


1 Answers

The x in f1 is a new variable only accessible within f1 and has no effect on the first, global x. The example code in your question could essentially be written like the following for clarity:

    var globalX = "outside";
    var f1 = function() {
      var localF1X = "inside f1";
    };
    f1();
    console.log(globalX); // → outside

    var f2 = function() {
      globalX = "inside f2";
    };
    f2();
    console.log(globalX); // → inside f2
like image 121
rgthree Avatar answered May 18 '26 07:05

rgthree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!