diff --git a/lib/internal/repl/await.js b/lib/internal/repl/await.js index ba138fdfe8c8d9..ec1d0c8823e107 100644 --- a/lib/internal/repl/await.js +++ b/lib/internal/repl/await.js @@ -221,22 +221,26 @@ function processTopLevelAwait(src) { return null; } - const last = body.body[body.body.length - 1]; - if (last.type === 'ExpressionStatement') { - // For an expression statement of the form - // ( expr ) ; - // ^^^^^^^^^^ // last - // ^^^^ // last.expression - // - // We do not want the left parenthesis before the `return` keyword; - // therefore we prepend the `return (` to `last`. - // - // On the other hand, we do not want the right parenthesis after the - // semicolon. Since there can only be more right parentheses between - // last.expression.end and the semicolon, appending one more to - // last.expression should be fine. - state.prepend(last, 'return ('); - state.append(last.expression, ')'); + for (let i = body.body.length - 1; i >= 0; i--) { + const node = body.body[i]; + if (node.type === 'EmptyStatement') continue; + if (node.type === 'ExpressionStatement') { + // For an expression statement of the form + // ( expr ) ; + // ^^^^^^^^^^ // node + // ^^^^ // node.expression + // + // We do not want the left parenthesis before the `return` keyword; + // therefore we prepend the `return (` to `node`. + // + // On the other hand, we do not want the right parenthesis after the + // semicolon. Since there can only be more right parentheses between + // node.expression.end and the semicolon, appending one more to + // node.expression should be fine. + state.prepend(node, 'return ('); + state.append(node.expression, ')'); + } + break; } return ( diff --git a/test/parallel/test-repl-preprocess-top-level-await.js b/test/parallel/test-repl-preprocess-top-level-await.js index 656b616b71d9e6..51b15e107f53bc 100644 --- a/test/parallel/test-repl-preprocess-top-level-await.js +++ b/test/parallel/test-repl-preprocess-top-level-await.js @@ -22,6 +22,8 @@ const testCases = [ `(async () => { return (await ${surrogate}) })()` ], [ 'await 0;', '(async () => { return (await 0); })()' ], + [ 'await 0;;;', + '(async () => { return (await 0);;; })()' ], [ `await ${surrogate};`, `(async () => { return (await ${surrogate}); })()` ], [ `await ${surrogate};`,