Google News
logo
CoffeeScript - Interview Questions
What is Lexical Scoping and Variable Safety in CoffeeScript?
The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.
outer = 1
changeNumbers = ->
  inner = -1
  outer = 10
inner = changeNumbers()​
var changeNumbers, inner, outer;
​
outer = 1;
​
changeNumbers = function() {
  var inner;
  inner = -1;
  return outer = 10;
};
​
inner = changeNumbers();​
Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. outer is not redeclared within the inner function, because it’s already in scope; inner within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.
Advertisement