{"record":{"id":"a550207c47cd82fc","repo":"karatelabs/karate","slug":"reduce-of-empty-array-with-no-initial-value","errorCode":null,"errorMessage":"Reduce of empty array with no initial value","messagePattern":"Reduce of empty array with no initial value","errorType":"exception","errorClass":"JsErrorException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/JsArrayPrototype.java","lineNumber":893,"sourceCode":"        // is acceptable churn against the much larger\n        // {@code (function(){return this.x}).reduce(...)} body of in-the-wild\n        // code that depends on natural {@code this} propagation.\n        JsCallable callable = requireCallable(args, \"Array.prototype.reduce\");\n        Object thisObj = context.getThisObject();\n        Object[] acc = new Object[1];\n        boolean[] hasAcc = {args.length >= 2};\n        if (hasAcc[0]) acc[0] = args[1];\n        specIterate(context, true, true, (k, v) -> {\n            if (!hasAcc[0]) {\n                acc[0] = v;\n                hasAcc[0] = true;\n                return true;\n            }\n            acc[0] = callable.call(context, new Object[]{acc[0], v, k, thisObj});\n            return true;\n        });\n        if (!hasAcc[0]) {\n            throw JsErrorException.typeError(\"Reduce of empty array with no initial value\");\n        }\n        return acc[0];\n    }\n\n    private Object reduceRight(Context context, Object[] args) {\n        JsCallable callable = requireCallable(args, \"Array.prototype.reduceRight\");\n        Object thisObj = context.getThisObject();\n        Object[] acc = new Object[1];\n        boolean[] hasAcc = {args.length >= 2};\n        if (hasAcc[0]) acc[0] = args[1];\n        specIterate(context, false, true, (k, v) -> {\n            if (!hasAcc[0]) {\n                acc[0] = v;\n                hasAcc[0] = true;\n                return true;\n            }\n            acc[0] = callable.call(context, new Object[]{acc[0], v, k, thisObj});\n            return true;","sourceCodeStart":875,"sourceCodeEnd":911,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/JsArrayPrototype.java#L875-L911","documentation":"Array.prototype.reduce without an initial value on an array with no elements has no seed for the accumulator, so the spec mandates a TypeError. Karate throws 'Reduce of empty array with no initial value' in its reduce implementation when the callback never ran (hasAcc still false).","triggerScenarios":"[].reduce(fn) or arr.reduce(fn) where arr is empty and no second (initialValue) argument is supplied.","commonSituations":"Summing/merging over data that turned out empty (empty JSON array from an API or empty karate response); filtering before reducing removed all elements; reduce used where reduceRight/initial value was intended.","solutions":["Provide an initial value: arr.reduce(fn, 0) (or [], {}, as appropriate)","Check the array is non-empty before reducing: if (arr.length === 0) return default;","Handle empty data at the source (server returned an empty list)","Catch the TypeError and return a default"],"exampleFix":"// before\nconst total = items.reduce((a, b) => a + b.price,);\n// after\nconst total = items.reduce((a, b) => a + b.price, 0);","handlingStrategy":"validation","validationCode":"if (!Array.isArray(items) || items.length === 0) return 0; // default seed","typeGuard":"function isNonEmptyArray(a) { return Array.isArray(a) && a.length > 0; }","tryCatchPattern":"try { return items.reduce(fn); } catch (e) { if (String(e.message).includes('Reduce of empty array')) return 0; throw e; }","preventionTips":["Always supply an initialValue to reduce","Check array emptiness after filtering before folding","Treat empty API responses as a first-class case in scripts"],"tags":["javascript","array","reduce","type-error"],"backgroundTag":"empty-required-field","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}