Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix description of variables having Javascript-like scope #7

Open
cubranic opened this issue Oct 10, 2013 · 3 comments
Open

Fix description of variables having Javascript-like scope #7

cubranic opened this issue Oct 10, 2013 · 3 comments

Comments

@cubranic
Copy link

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
Copy link

Protonk commented Oct 16, 2013

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
Copy link
Owner

tdsmith commented Oct 17, 2013

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
Copy link

Protonk commented Oct 21, 2013

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants