Hint
JS inserts ; in specific places — return on its own line is the classic trap
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