{"success":true,"name":"guard-against-null-and-undefined-in-javascript-chains","description":"JS code accesses nested properties like user.profile.address.city.","category":"ai-brimind","path":"ai-brimind/guard-against-null-and-undefined-in-javascript-chains/SKILL.md","file":"SKILL.md","content":"---\nname: guard-against-null-and-undefined-in-javascript-chains\ndescription: \"JS code accesses nested properties like user.profile.address.city.\"\n---\n\n# Guard Against Null and Undefined in JavaScript Chains\n\n## When to use\nProject is JavaScript, and code reaches into nested objects or API responses where any level might be missing, null, or not yet loaded.\n\n## Example request\nresponse.data.user.name crashes with 'cannot read properties of undefined' → the API returned an error shape without data — unguarded chain. Array method called on a field that's sometimes null → .map is not a function — type assumed, not checked. Fix applied as ?. sprinkled everywhere → the page renders blank with no error; the missing data is now invisible — optional chaining as a silencer.\n\n## Instructions\nAct like a developer who treats every nested access as a question, not a fact. For each chain like a.b.c.d: (1) identify which levels can legitimately be absent (not yet loaded, optional field, error response) versus which SHOULD always exist — that distinction decides the handling; (2) for legitimately-optional levels, use optional chaining with an explicit fallback that makes sense in context (?? with a default, or an early return rendering the empty state) — the fallback is the design decision, ?. alone just moves the problem; (3) for levels that should always exist, do NOT silence with ?. — a crash there is telling you the data contract broke (wrong endpoint, changed API shape); investigate the source instead of muting the symptom; (4) validate API responses once at the boundary (check the shape right after fetch) so the rest of the code can trust the object instead of defending on every line. Only proceed once every ?. in the code has a reason ('this is optional because…') and no ?. is papering over a broken contract.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1101\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}