Amber Dev Singh
Amber Dev Singh

Reputation: 11

I cannot return an object until and unless the curly bracket is placed right next to the return statement

compClasses: function() {
    /* IT DOES NOT WORK LIKE THIS */
    return 
    {
        major: this.valA,
        minor: this.valB
    }
    /* BUT WORKS LIKE THIS KINDLY TAKE NOTICE OF THE PLACEMENT OF CURLY BRACKETS */
    return {
        major: this.valA,
        minor: this.valB
    }
}

Upvotes: 1

Views: 74

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16079

JavaScript automatically inserts semicolons (or ends statements) when needed. If you write

return
{
    major: this.valA,
    minor: this.valB
}

the return statement is executed directly (like if you'd write return;). If you write

return {
    major: this.valA,
    minor: this.valB
}

the complete object is returned instead. The semicolon is added after the object.


The rules for automatic insertions of semicolons are as followed (source):

  1. when the next line starts with code that breaks the current one (code can spawn on multiple lines)
  2. when the next line starts with a }, closing the current block
  3. when the end of the source code file is reached
  4. when there is a return statement on its own line
  5. when there is a break statement on its own line
  6. when there is a throw statement on its own line
  7. when there is a continue statement on its own line

Upvotes: 2

Related Questions