tdsmith / aRrgh

A newcomer's (angry) guide to data types in R
Other
307 stars 14 forks source link

Fix description of variables having Javascript-like scope #7

Open cubranic opened 10 years ago

cubranic commented 10 years ago

Like PHP and Javascript, variables have function (not block) scope.

While it's true that variable scope is not per-block, it's not the same as in JavaScript, where local variables are hoisted to top of the function:

Example from Mozilla.org:

(function() {
  console.log(myvar); // undefined (but not an error)
  var myvar = "local value";
})();

Try the same in R and you'll get "Error in print(myvar) : object 'myvar' not found":

(function() {
  print(myvar) # error
  myvar <- "local value"
}()

But yes, there is no block scope:

(function() {
  if (TRUE) {
    myvar <- "local variable"
  }
  print(myvar)
})()

will print "local variable". For block-scope, you can use local:

(function() {
  if (TRUE) {
    local({
      myvar <- "local variable"
    })
  }
  print(myvar)
})()

will throw: "Error in print(myvar) : object 'myvar' not found"

Protonk commented 10 years ago

I think aside from variable hoisting, it's pretty fair to describe the scoping as JS-like. And since hoisting is (arguably) a quirk in JS and lack of hoisting is not a quirk in R, I don't think we need a clarification. I don't think we're making a rigorous claim, just giving a gist.

Eventually ES6 implementations will start to use let and we'll have block scoping in JS, but that's another story. :)

tdsmith commented 10 years ago

Hello; thanks for the feedback! I think the relatively narrow claim the text makes (that neither Javascript or R has block scope) is correct and is not likely to be confusing, but maybe I'm underestimating the importance of hoisting to Javascript developers.

Protonk commented 10 years ago

@tdsmith It's not important, strictly speaking. You need to know about it to reason about the code, but it's not really a matter of scope. Hoisting works within a scope and impacts only the resolution order for variable definitions. Here is a broad overview.