{
"id": "article-keyed-destructure",
"type": "article",
"dataComponent": "article",
"heading": {
"title": "Destructuring Keyed Arrays to Variables",
"badges": ["ARTICLE"]
},
"synopsis": "Lava supports destructuring assignment from keyed arrays directly into variables, inspired by JS/Python destructuring. Use the `:key` label syntax for clean multi-variable binding.",
"sections": [
{
"type": "heading",
"level": 2,
"text": "Basic Usage"
},
{
"type": "codeBlock",
"code": ":a, :b = [a:10212, b:2200, c:33330]\nslog(a) # prints 10212\nslog(b) # prints 2200"
},
{
"type": "list",
"items": [
"`:a, :b = [a:..., b:..., ...]` assigns variables `a` and `b` from the matching keys of the keyed array.",
"Any variable not found in the array is set to `_` (the placeholder)."
]
},
{
"type": "heading",
"level": 2,
"text": "Arbitrary Key Order & Subset"
},
{
"type": "codeBlock",
"code": ":x, :y, :z = [y:5, z:10, x:99]\nslog(x) # 99\nslog(y) # 5\nslog(z) # 10"
},
{
"type": "list",
"items": [
"You can specify any subset of keys you want.",
"The order of variables does not have to match the array’s order."
]
},
{
"type": "heading",
"level": 2,
"text": "Missing Keys"
},
{
"type": "codeBlock",
"code": ":foo, :bar = [foo:123]\nslog(foo) # 123\nslog(bar) # _"
},
{
"type": "paragraph",
"text": "If a key is missing, the variable receives the `_` placeholder. This makes destructuring robust against missing fields."
},
{
"type": "heading",
"level": 2,
"text": "Destructuring in Functions"
},
{
"type": "codeBlock",
"code": "fn handleUser(user) {\n :name, :age = user\n slog(name)\n slog(age)\n}\n\nhandleUser([name:\"Alice\", age:30, city:\"Paris\"])"
},
{
"type": "paragraph",
"text": "Destructuring works inside any block or function scope."
},
{
"type": "heading",
"level": 2,
"text": "Summary"
},
{
"type": "list",
"items": [
"Use `:var` syntax in assignment to pull values from a keyed array.",
"Any number of variables can be extracted at once.",
"Order of variables is arbitrary.",
"Missing keys yield `_`."
]
}
]
}