0

I am having this strange issue at times when using coffeescript. Example below:

Coffeescript:

$scope.function1 = () -> console.log("function 1")

$scope.function2 = () -> console.log("function 2")

Javascript:

$scope.function1 = function() { console.log("function 1"); return $scope.function2 = function () { console.log("function 1"); }

Why is the second function goes inside the first one? Any help with this is highly appreciated. It is not happening all the time though.

1
  • 3
    Double-check your indentation, that must be the issue. Commented Aug 25, 2015 at 7:20

1 Answer 1

3

In CoffeeScript, indentation is meaningful. Your code as posted in your question translates as you want. But if the second function is indented relative to the first:

$scope.function1 = () ->
  console.log("function 1")

  $scope.function2 = () ->
    console.log("function 2")

...it translates incorrectly in the way you've shown.

Be sure also to be consistent in your use of spaces or tabs.

But again, as quoted in the question, it's fine:

$scope.function1 = () ->
    console.log("function 1")

$scope.function2 = () ->
    console.log("function 2")

becomes

$scope.function1 = function() {
  return console.log("function 1");
};

$scope.function2 = function() {
  return console.log("function 2");
};
Sign up to request clarification or add additional context in comments.

3 Comments

I too thought indentation must be the problem. But even when I remove everything and do it from scratch this issue occurs. When I rearrange the functions like moving the scope function from top of the controller to bottom of the controller, it is getting fixed. Also an empty return statement in the first function sometimes fixes it. Is it something to do with my text editor settings related to tabs/spaces etc? I am using sublimetext 3. Thanks.
@Saravanaselvan: Copying and pasting your question's version into the "Try CoffeeScript" widget on the coffeescript.org site converts it properly. So it's definitely indentation. I'd make sure your editor is set to insert spaces, not tabs, as that is usually going to be more reliable. (Well, I'd just not use CoffeeScript -- and this is one of the reasons. :-) Esp. now that ES6 is finalized as there are good transpilers for it.)
Thanks for your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.