{"record":{"id":"a8cbf561528f9d51","repo":"karatelabs/karate","slug":"a-function-declaration-may-not-be-the-body-of-where","errorCode":null,"errorMessage":"a function declaration may not be the body of ${where}","messagePattern":"a function declaration may not be the body of (.+?)","errorType":"exception","errorClass":"ParserException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/parser/JsParser.java","lineNumber":758,"sourceCode":"        }\n        return false;\n    }\n\n    /** Throws if any direct {@code STATEMENT} child of {@code node} is itself a\n     *  function declaration (its first non-token child is an {@code FN_EXPR}) — the\n     *  body of `if` / loop / labelled clauses is a Statement, and FunctionDeclaration\n     *  is a StatementListItem only. A braced body (BLOCK) is fine. */\n    private static void checkNoFunctionDeclarationBody(Node node, String where) {\n        for (int i = 0, n = node.size(); i < n; i++) {\n            Node child = node.get(i);\n            if (child.isToken() || child.type != NodeType.STATEMENT) {\n                continue;\n            }\n            for (int j = 0, m = child.size(); j < m; j++) {\n                Node inner = child.get(j);\n                if (!inner.isToken()) {\n                    if (inner.type == NodeType.FN_EXPR) {\n                        throw new ParserException(\n                                \"a function declaration may not be the body of \" + where);\n                    }\n                    break; // first non-token child decides\n                }\n            }\n        }\n    }\n\n    /** Throws if any direct {@code STATEMENT} child of {@code node} is itself a\n     *  LexicalDeclaration ({@code let}/{@code const}) or a ClassDeclaration — the body\n     *  of an `if`/`else`/loop clause is a Statement, and both are Declarations, not\n     *  Statements (§13.6/§14.x). A {@code var} declaration hoists and stays legal; a\n     *  braced body (BLOCK) is fine. Mode-independent — there is no Annex B carve-out\n     *  for these the way there is for FunctionDeclaration in an `if` clause. */\n    private static void checkNoLexicalOrClassDeclarationBody(Node node, String where) {\n        for (int i = 0, n = node.size(); i < n; i++) {\n            Node child = node.get(i);\n            if (child.isToken() || child.type != NodeType.STATEMENT) {","sourceCodeStart":740,"sourceCodeEnd":776,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/parser/JsParser.java#L740-L776","documentation":"In ECMAScript, the body clause of `if`/`else`, loops, and labelled statements is a single Statement, while a function declaration is a StatementListItem, not a Statement. Karate's JS parser enforces this strictly and rejects `if (x) function f() {}` style code instead of tolerating non-standard Annex B slop. A braced block body is the legal form.","triggerScenarios":"Writing an unbraced clause whose body is a function declaration, e.g. `if (cond) function f() {}`, `while (x) function f() {}`, or `label: function f() {}`, in any Karate JS expression/script parsed by JsParser.","commonSituations":"Code written by habit from sloppy browser environments that tolerate `if (x) function f(){}`; minified or transpiled code pasted in; authors omitting braces to save a line.","solutions":["Wrap the function declaration in braces: `if (cond) { function f() {} }`.","Better, declare the function before/outside the clause and just call it in the clause.","Convert to a function expression assigned to a variable: `if (cond) { const f = () => {}; }`.","Run the same code in Node --strict to catch these before putting them in Karate scripts."],"exampleFix":"// before\nif (ready) function init() { start(); }\n// after\nif (ready) { function init() { start(); } init(); }","handlingStrategy":"validation","validationCode":"// reject unbraced clauses whose body starts with 'function'\nfunction hasUnbracedFnBody(src) {\n  return /(^|[^\\w$])(if|else|for|while|do|\\w+:)\\s*function\\s*[\\w$]*\\s*\\(/.test(src);\n}\nif (hasUnbracedFnBody(src)) throw new Error('brace the function declaration body');","typeGuard":null,"tryCatchPattern":"try {\n  return karate.eval(script);\n} catch (e) {\n  if (String(e.message).includes('may not be the body of')) {\n    throw new Error('Add braces around the clause body in: ' + script);\n  }\n  throw e;\n}","preventionTips":["Always brace if/else/loop bodies — never rely on single-statement clauses.","Declare functions at statement-list positions, not as clause bodies.","Enable a linter (ESLint consistent-return / no inner declarations style rules) on embedded JS.","When transpiling code into Karate scripts, keep the braces the transpiler emits."],"tags":["javascript","parser","syntax-error","function-declaration"],"backgroundTag":"invalid-syntax","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}