Skip to content

Selecting variable declarations

Variables can be declared in any of the following generalized forms:

javascript
var x = 1;
let {x} = {};
const [x] = a;

A variable declaration has three selectable properties:

  1. its name, which is what's on the left-hand side; or the identifier x and patterns {x}, [x] in the snippet above
  2. its initializer, which is the expression on the right-hand side; or the 1, {}, and a in the snippet above
  3. the kind of its binding; var, let, or const

Like (fun) for function declarations, (var) selects variable declarations and has the following signature:

clojure
(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:

javascript
let x = 1;
//  ^

Selecting an identifier binding (i.e. name) can be done using the (id) selector:

clojure
(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:

javascript
const { meta, users: [] } = await loadUsers();

We can tell what kind of properties are being destructured from the call to loadUsers() through the following selector:

clojure
(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:

clojure
(is var)    ; var x
(is let)    ; let x
(is const)  ; const x

Copyright © 2022-present Semantic Works, Inc.