{"record":{"id":"4409832110dc5c0d","repo":"elsa-workflows/elsa-core","slug":"variable-fornode-variablename-is-not-declared-use-var","errorCode":null,"errorMessage":"Variable '{forNode.VariableName}' is not declared. Use 'var {forNode.VariableName}' to declare a new variable in the for loop.","messagePattern":"Variable '(.+?)' is not declared\\. Use 'var (.+?)' to declare a new variable in the for loop\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/modules/Elsa.Dsl.ElsaScript/Compiler/ElsaScriptCompiler.cs","lineNumber":308,"sourceCode":"        return forEachActivity;\n    }\n\n    private async Task<IActivity> CompileForAsync(ForNode forNode, CancellationToken cancellationToken = default)\n    {\n        Variable loopVariable;\n\n        if (forNode.DeclaresVariable)\n        {\n            // Create a new loop variable\n            loopVariable = new Variable<int>(forNode.VariableName, 0);\n            _variables[forNode.VariableName] = loopVariable;\n        }\n        else\n        {\n            // Reuse existing variable\n            if (!_variables.TryGetValue(forNode.VariableName, out loopVariable!))\n            {\n                throw new InvalidOperationException($\"Variable '{forNode.VariableName}' is not declared. Use 'var {forNode.VariableName}' to declare a new variable in the for loop.\");\n            }\n        }\n\n        var start = CompileExpressionAsInput<int>(forNode.Start);\n        var end = CompileExpressionAsInput<int>(forNode.End);\n        var step = CompileExpressionAsInput<int>(forNode.Step);\n        var body = await CompileStatementAsync(forNode.Body, cancellationToken);\n\n        var forActivity = new For\n        {\n            Start = start,\n            End = end,\n            Step = step,\n            OuterBoundInclusive = new Input<bool>(forNode.IsInclusive),\n            CurrentValue = new Output<object?>(loopVariable),\n            Body = body\n        };\n","sourceCodeStart":290,"sourceCodeEnd":326,"githubUrl":"https://github.com/elsa-workflows/elsa-core/blob/fe9217bdfa0e27f0e09e45006eb6898f616e513d/src/modules/Elsa.Dsl.ElsaScript/Compiler/ElsaScriptCompiler.cs#L290-L326","documentation":"CompileForAsync reuses an existing declared variable as the for-loop counter; if forNode.VariableName was never declared with 'var', the compiler throws InvalidOperationException with a message suggesting the 'var' declaration. Like foreach, the for statement does not implicitly declare its loop variable.","triggerScenarios":"A for statement whose VariableName is absent from the compiler's _variables dictionary when the 'else' reuse path is taken (no inline declaration provided).","commonSituations":"C-style habits (for (i = 0; ...)) without declaring i, a typo between declaration and loop usage, or the variable declared in an enclosing scope the compiler's variable table does not include.","solutions":["Declare the counter before the loop: var i; then for (i = 0; i < 10; i += 1) { ... }.","Ensure the declared name matches the loop variable exactly.","If the parser supports an inline declaration form, use it so the variable is created by the loop itself.","Catch the exception and surface a hint to declare the loop variable."],"exampleFix":"// before\nfor (i = 0; i < 10; i += 1) { } // i undeclared\n// after\nvar i;\nfor (i = 0; i < 10; i += 1) { }","handlingStrategy":"validation","validationCode":"const declared = collectVarDeclarations(ast); const missing = collectForVars(ast).filter(v => !declared.has(v.name)); if (missing.length) throw new Error('Declare with var: ' + missing.map(m => m.name).join(', '));","typeGuard":"function forVarsDeclared(ast) { const declared = declaredVarNames(ast); return ast.forNodes.every(n => declared.has(n.variableName)); }","tryCatchPattern":"try { await compileScript(script); } catch (InvalidOperationException ex) when (ex.Message.Contains('is not declared')) { showDeclareVarFix(ex); }","preventionTips":["Always emit 'var i;' before for loops when generating scripts.","Lint for undeclared identifiers before compilation.","Avoid C-style implicit declarations; ElsaScript requires explicit 'var'."],"tags":["dsl","variables","compiler"],"backgroundTag":"missing-required-argument","analyzedSha":"fe9217bdfa0e27f0e09e45006eb6898f616e513d","analyzedAt":"2026-09-13T20:32:34.702Z","contentChangedAt":"2026-09-13T20:32:34.702Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}