1.5 KiB
1.5 KiB
JavaScript Silent Crash: Block-Scoped const in try
Pattern: A const (or let) declared inside a try {} block is referenced
outside the block. JavaScript throws a ReferenceError that silently crashes
async event handlers — no error visible in the UI, no console output if the
handler is an addEventListener callback calling an async function.
Example
async function handleFinancialCompletion() {
// ...
try {
const roData = getROData(roId); // block-scoped to try
// ...
} catch (e) {}
// BUG: roData is undefined here — ReferenceError
if (roData) {
roData.statusHistory.push({ ... });
}
// ...
}
Why it's silent
The completeBtn.addEventListener('click', (e) => { handleFinancialCompletion(); })
does NOT catch the rejected promise from the async function. The ReferenceError
propagates as an unhandled promise rejection — which browsers log but the UI
shows nothing. The user sees "nothing happens."
Fix
Declare the variable OUTSIDE the try block:
const roData = getROData(roId); // outside try
try {
const servicesLines = roData?.services ? ...;
// ...
} catch (e) {}
// roData is accessible here
if (roData) { ... }
Detection
Grep for const.*=.*try patterns or any variable accessed after a } catch
that was declared inside the try:
grep -n 'const ' file.js | while read line; do
# Check if any const declared in try block is used after catch
...
done