{"record":{"id":"77fc60dc72e6fb0e","repo":"karatelabs/karate","slug":"cannot-convert-undefined-or-null-to-object","errorCode":null,"errorMessage":"Cannot convert undefined or null to object","messagePattern":"Cannot convert undefined or null to object","errorType":"exception","errorClass":"JsErrorException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/JsObjectConstructor.java","lineNumber":227,"sourceCode":"        }\n        return new JsArray(result);\n    }\n\n    /** Spec ToObject preamble: Object.keys/values/entries throw TypeError on\n     *  null/undefined ahead of any iteration (test262\n     *  Object/keys/15.2.3.14-1-4 and -1-5). */\n    private static void requireObjectCoercible(Object[] args, String op) {\n        if (args.length < 1 || args[0] == null || args[0] == Terms.UNDEFINED) {\n            throw JsErrorException.typeError(op + \" called on null or undefined\");\n        }\n    }\n\n    private Object assign(Context context, Object[] args) {\n        if (args.length == 0) {\n            return new LinkedHashMap<>();\n        }\n        if (args[0] == null || args[0] == Terms.UNDEFINED) {\n            throw JsErrorException.typeError(\"Cannot convert undefined or null to object\");\n        }\n        CoreContext cc = context instanceof CoreContext c ? c : null;\n        // §20.1.2.1: the target itself is mutated and returned — identity is\n        // observable (`Object.assign(t, src) === t`), and step 4c is\n        // Set(to, key, value, true), so target setters fire and a rejected\n        // write throws. Spread/rest keep CreateDataProperty semantics via\n        // Terms.copyDataProperties; the two operations are not the same seam.\n        // ToObject approximation for a primitive target: no mutable wrapper\n        // exists, so copy into a fresh map that stands in for the wrapper —\n        // identity/setter semantics only apply to real object targets\n        Object target = args[0] instanceof ObjectLike || args[0] instanceof Map<?, ?>\n                ? args[0] : new LinkedHashMap<String, Object>();\n        for (int i = 1; i < args.length; i++) {\n            if (cc != null && cc.isError()) {\n                break; // a source getter threw — nothing copies past it\n            }\n            // §20.1.2.1 step 4: both key partitions copy — the symbol store has\n            // no string key, so it is walked separately","sourceCodeStart":209,"sourceCodeEnd":245,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/JsObjectConstructor.java#L209-L245","documentation":"Object.assign requires a coercible target object. Per §20.1.2.1, when the first argument is null or undefined the engine throws a TypeError; the target is mutated and returned, so a null target cannot proceed.","triggerScenarios":"Object.assign(null, src), Object.assign(undefined, {...}), or Object.assign(maybeNull, opts) where maybeNull came from an absent config/JSON field.","commonSituations":"Merging default options onto a config object that was never initialized; spreading onto a missing response object.","solutions":["Ensure the target object exists before assigning: initialize it to {} if missing.","Use Object.assign({}, src) to build a fresh object instead of mutating a possibly-null target.","Guard: `if (target != null) Object.assign(target, src)`.","In Karate JS, back the variable with a default at definition time: `var target = base || {}`."],"exampleFix":"// before\nvar merged = Object.assign(config.extra, defaults);\n// after\nvar merged = Object.assign(config.extra || {}, defaults);","handlingStrategy":"type-guard","validationCode":"if (target == null) { target = {}; }\nObject.assign(target, src);","typeGuard":"function isTarget(v) { return v !== null && v !== undefined; }","tryCatchPattern":"try { Object.assign(target, src); } catch (e) { if (String(e).indexOf('Cannot convert undefined or null') !== -1) { target = Object.assign({}, src); } else { throw e; } }","preventionTips":["Always pass a literal {} target when building fresh objects","Initialize config objects at startup","Avoid mutating possibly-null targets"],"tags":["javascript","typeerror","object-assign"],"backgroundTag":"null-argument","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"}