Programming concepts
Validated preference decoding
Programming pattern: parse a stored string and validate its allowed shape before deriving application state.
Formal Syntax & Structure
javascript syntaxjavascript
decode(storedText)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| storedText | string | null | Serialized preference or absent value. |
Return Value
string
Validated theme or documented default in this example.
Working Example
Example Snippetjavascript
function decode(raw){try{const x=JSON.parse(raw);return x&&x.v===1&&["light","dark"].includes(x.theme)?x.theme:"light";}catch{return "light";}}console.log(decode('{"v":1,"theme":"dark"}'),decode("bad"),decode('{"v":2,"theme":"dark"}'));