The Grouparoo Blog

Unused Variables in Destructured Arrays

Tagged in Engineering Notes 
By Pedro S Lopez on 2021-03-16

Last week when working on Grouparoo's OneSignal integration, I wrote a quick CLI script to create users in their system that we could use for testing. This script would take in a single argument, which would be the external_user_id on OneSignal:

$ ./create_user <external_user_id>

Parsing command-line arguments

To allow parsing command-line arguments, Node provides process.argv. This property returns an array that contains all arguments passed when the process was launched. The first two arguments are always the path to node and the path to the JS file being executed, respectively. For instance, the previous example would return the following array:

// process.argv
["/path/to/node", "/path/to/create_user", "<external_user_id>"];

To unpack this array and use these variables in our code, we could use JavaScript's array destructuring features:

const [nodePath, scriptPath, externalUserId, ...otherArgs] = process.argv;

// Do something with the externalUserId

Taking a closer look at the example above, you'll notice that we're not actually doing anything with the first two variables.

Ignoring unused variables

A common practice is to prefix the unused variables with an underscore to clearly indicate that they will not be used:

const [_nodePath, _scriptPath, externalUserId] = process.argv;

Something very similar to this is what I have usually done in the past, but I was writing this script pretty quickly and (accidentally) omitted the variable names, writing this instead:

const [, , externalUserId] = process.argv;

Much to my surprise, when I saved the file Prettier came in and formatted it without any complaints. It turns out you don't even need to assign the unused variables!

GitHub screenshot: Surprised comments after learning about ignoring variables

This works anywhere in the array, so you can also do this with elements in the middle:

// Only assign the first and fourth elements
const [one, , , four] = ["one", "two", "three", "four"];

It's great to learn something new about things you use so frequently!

Get Started with Grouparoo

Start syncing your data with Grouparoo Cloud

Start Free Trial

Or download and try our open source Community edition.