1

My Angular code does not work when written as follows:
Here it is:

app.directive("strength", function() {
return 
{
    require: "superhero",
    link: function(scope, element, attrs, superheroCtrl) {
        superheroCtrl.addStrength();
    }
  }
})

However, when the return object's first curly bracket is on the same line as the return statement, the code works: Here's the code that works.

app.directive("strength", function() {
    return {
        require: "superhero",
        link: function(scope, element, attrs, superheroCtrl) {
            superheroCtrl.addStrength();
        }
    }
})

Am I doing something else incorrect?
How else can this be solved?
Thanks!

5
  • Have you added the javascript file to your page? Commented Nov 28, 2014 at 2:45
  • 4
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 28, 2014 at 2:47
  • Yes. The JS file is between <script> tags in the html and I have also added the angular src Commented Nov 28, 2014 at 2:49
  • Thanks @PSL . So the answer is: a semicolon is automatically inserted after the return statement if there is nothing else on the same line. Commented Nov 28, 2014 at 2:54
  • @raneshu yes more precisely The return statement is affected by automatic semicolon insertion (ASI). There is no line terminator between the return keyword and the expression allowed. Commented Nov 28, 2014 at 2:57

1 Answer 1

3

This is related to the syntax. In the first case, it causes automatic semicolumn insertion right after the return statement, and the second statement of defining an object literal with key/value just becomes a syntax error unless it is assigned to.

So your statement is equivalent to:-

return; //<-- Statement terminated here
 {
    require: "superhero", //<-- this will be a syntax error
    link: function(scope, element, attrs, superheroCtrl) {
        superheroCtrl.addStrength();
    }
  };

The return statement is affected by automatic semicolon insertion (ASI). There is no line terminator between the return keyword and the expression allowed.

Sign up to request clarification or add additional context in comments.

Comments

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.