Comments and Automatic Semicolon Insertion

JavaScript allows line comments with // and block comments with /* ... */. Semicolons are generally optional because ECMAScript defines Automatic Semicolon Insertion (ASI). However, ASI does not simply insert a semicolon at every newline. It operates according to grammar rules and restricted productions.

A classic example is a return followed by a newline. Because of the grammar rules, the newline can terminate the return statement before the expression.

The Return-Newline Trap
function getUser() {
  return
  {
    name: 'Suriya'
  };
}

console.log(getUser());
💡 The newline after return causes the statement to terminate, so the function returns undefined. Formatting can therefore affect behavior in specific JavaScript grammar situations.
Key Takeaways
  • ASI is grammar-driven rather than simply newline-driven.
  • Be especially careful after return, throw, break, and continue.
  • Consistent formatting and semicolon conventions reduce ambiguity.
Knowledge Check

What does the function in the example return?