Selecting variable declarations
Variables can be declared in any of the following generalized forms:
var x = 1;
let {x} = {};
const [x] = a;
A variable declaration has three selectable properties:
- its name, which is what's on the left-hand side; or the identifier
x
and patterns{x}
,[x]
in the snippet above - its initializer, which is the expression on the right-hand side; or the
1
,{}
, anda
in the snippet above - the kind of its binding;
var
,let
, orconst
Like (fun)
for function declarations, (var)
selects variable declarations and has the following signature:
(var [binding] [init] [kind])
Selecting a variable declaration by binding
The binding can be a plain identifier, like a name, or a destructuring pattern that binds names in turn. The next chapter addresses how to select patterns, so for now we'll concern ourselves only with the identifier names:
let x = 1;
// ^
Selecting an identifier binding (i.e. name) can be done using the (id)
selector:
(var (id x)) ; var x
(var (id /x/)) ; var yxxy
Selecting a variable declaration by initializer
The initializer can be any valid JavaScript expression, so you can use any of the corresponding selectors. When it comes to declarations, you're usually interested in the inverse of what you can select: if you want to know the name, you'll likely be selecting by the initializer, and vice versa.
For example, consider the following declaration:
const { meta, users: [] } = await loadUsers();
We can tell what kind of properties are being destructured from the call to loadUsers()
through the following selector:
(var _ (call loadUsers))
Which would match the entire declaration, including the binding { meta, users: [] }
.
Selecting a variable declaration by kind
The last selectable property of a variable declaration, kind
, might be relevant when attempting to migrate from one binding kind to another, although it's rarely useful with the auto-formatting tools available today as they usually take care of it.
In any case, should you need to confine the selection to a variable declared one way or another, you can use the (is)
selector that we used previously for function declarations:
(is var) ; var x
(is let) ; let x
(is const) ; const x