Question

I converted my CoffeeScript code to JavaScript using http://js2coffee.org

ResetControls = ->
  $("#menu_item_url").val ""
  $("#menu_item_name").val ""
  $("#resource_id").prop "selectedIndex", 0
  $("#resource_type_id").prop "selectedIndex", 0

It converted it to:

var ResetControls;

ResetControls = function() {
  $("#menu_item_url").val("");
  $("#menu_item_name").val("");
  $("#resource_id").prop("selectedIndex", 0);
  return $("#resource_type_id").prop("selectedIndex", 0);
};

The first line in the converted JavaScript code suggests that its some kind of a best practice to put var keyword before variable name, when assigning function to a variable. Is it so? How?

In my understanding, var comes handy in recursive calls where your intention is to make copies of variables inside the recursive function (otherwise they will be shared or remain static between the recursive calls ).

Is there any other significance of var?

Was it helpful?

Solution

Yes, you have to put var before variable name. In this way you are declaring variable in the current scope - otherwise JS will search for it in outer scopes and if not declared in any scope - will make it global. As far as I know, in strict mode, even global variables should be declared with var in the global space.

P.S. This is valid for all variables, not only for those that you assign a function to

OTHER TIPS

And another reason is garbage collection. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top