Programming concepts

Validated preference decoding

Try the free JavaScript compiler

Programming pattern: parse a stored string and validate its allowed shape before deriving application state.

Formal Syntax & Structure

javascript syntaxjavascript
decode(storedText)

Parameters & Attributes

NameTypeDescription
storedTextstring | nullSerialized 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"}'));
JavaScript Reference