🟡 MediumCore JS📖 Theory Question

What is Automatic Semicolon Insertion (ASI) and what are its gotchas?

💡

Hint

JS inserts ; in specific places — return on its own line is the classic trap

Full Answer

JavaScript automatically inserts semicolons in certain places during parsing to handle missing semicolons.

ASI rules (simplified): JS inserts ; when the next token would make the code invalid, and at the end of file.

// Classic trap: return on its own line
function getObj() {
  return    // ← ASI inserts ; HERE
  {
    data: 1  // unreachable!
  }
}
getObj(); // undefined! NOT the object

// Fix: opening brace on SAME line as return
function getObj() {
  return {
    data: 1
  };
}

// Trap 2: lines starting with (, [, /, +, -
const a = 1
const b = 2
[a, b].forEach(x => console.log(x)) // PARSED AS: 2[a,b].forEach(...)
// TypeError: Cannot read properties of undefined

// Fix: add semicolon to previous line, OR start with ;
const b = 2;
;[a, b].forEach(x => console.log(x)) // safe defensive semicolon
💡 Safest rule: always put return values on the same line as return. If not using semicolons, use defensive semicolons before lines starting with [, (, or /.

More Core JS Questions

🟢 EasyWhat is the difference between var, let, and const?🟢 EasyExplain closures with a practical example.🟢 EasyWhat is hoisting in JavaScript?🟢 EasyExplain the event loop, call stack, and microtask queue.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint