Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a variable to be local in coffeescript?

Tags:

coffeescript

Given the following code:

outer=1
f=->
  local=1
  outer=0
  local+outer

coffeescript creates a var for local but re-ueses outer:

var f, outer;

outer = 1;

f = function() {
  var local;
  local = 1;
  outer = 0;
  return local + outer;
};

Which is what your expect.

However, if you use a local variable in a function it depends on the outer scope if the variable is declared local or not. I know this is a feature, but it was causing some bugs, because I have to check all outer scopes for variables with the same name (which are declared before my function). I wonder if there is a way to prevent this type of bug by declaring variables local?

like image 723
Michael_Scharf Avatar asked Aug 14 '13 11:08

Michael_Scharf


People also ask

How do you create a local variable?

Right-click an existing front panel object or block diagram terminal and select Create»Local Variable from the shortcut menu to create a local variable. A local variable icon for the object appears on the block diagram. You also can select a local variable from the Functions palette and place it on the block diagram.

How do you create a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

How do you make a function in CoffeeScript?

The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below.


2 Answers

This kind of error usually comes up when you aren't using appropriately descriptive variable names. That said, there is a way to shadow an outer variable, despite what the accepted answer says:

outer=1
f=->
  do (outer) ->
    local=1
    outer=0
    local+outer

This creates an IIFE, with outer as it's one argument. Function arguments shadow outer variables just like the var keyword, so this will have the behavior you expect. However, like I said, you should really just name your variables more descriptively.

like image 159
Aaron Dufour Avatar answered Sep 20 '22 21:09

Aaron Dufour


No, that feature is explicitly not available in CoffeeScript (emphasis mine):

This behavior is effectively identical to Ruby's scope for local variables. Because you don't have direct access to the var keyword, it's impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that you're not reusing the name of an external variable accidentally, if you're writing a deeply nested function.

like image 27
Joachim Sauer Avatar answered Sep 22 '22 21:09

Joachim Sauer