Variable scope

Posted by jmls on 08-Jul-2012 12:07

I am trying to learn Javascript at the moment (urghh!) and came across the following scenario

var scope = "global";

function wtf() {

  console.log(scope);

  var scope = "local";

  console.log(scope);

}

wtf();

and the Progress version

def var scope as char init "global".

function wtf returns logical ():
  message scope view-as alert-box.

  def var scope as char init "local".

  message scope view-as alert-box.

end function.

wtf().

Now:

1) What would you expect to see with the a) javascript: two console.log statements and b) Progress: the two message statements ?

2) Why ?

Hint: I prefer the progress version

All Replies

Posted by bronco on 09-Jul-2012 03:52

Well, Julian I guess I don't have to explain the "downsides" of using globals ;-)

If you would have used console.log(this.scope) you would have seen "global".

The reason why you're seeing this behaviour is because in Javascript functions are objects. And in Javascript objects have a prototype. A function in Javascript has a link to the Function.prototype. This Function.prototype hasn't got a scope property declared, that's why you see undefined.

I know this all sounds a bit weird when you think about this from a class based OO perspective, but Javascript isn't class based.

If you want to read more about Javascript behaviour I suggest you read the "Javascript, the good parts " (yes, there are quite a few) from O'Reilly. When you're finished reading you'll probably see that Javascript is quite a different beast then its C-style syntax suggests.

Posted by bronco on 09-Jul-2012 03:59

PS. My personal Javascript favorite is that months are 0-based (ie January is 0, zero, instead of 1, one)...

Posted by JamesDev on 13-Jul-2012 21:09

1a.) The first log statement is undefined and the second is "local".

2.) Javascript has a concept called variable hoisting. Essentially, anywhere you declare a variable, that declaration gets "hoisted" to the top of the scope.

Therefore

function wtf() {
  console.log(scope);
  var scope = "local";
  console.log(scope);
}

Is the equivalent to

function wtf() {
  var scope;
  console.log(scope);
  scope = "local";
  console.log(scope);
}

Posted by jmls on 14-Jul-2012 04:30

yeah, once I got over the "wtf" (what the f) moment I went on to find out exactly wtf (why the f) did it do that, and up popped "hoisting" 

It's the violation of "the principle of least surprisethat got me with this .

It's also interesting that the Progress paradigm fitted exactly into my expectations - but is that because I am a progress guy ?

How do other languages like C, C#, php, python, ruby or pascal behave in this scenario ?

This thread is closed