DEV Community

Cover image for Prefix Unused Variables With Underscore
Daniel Bellmas
Daniel Bellmas

Posted on

Prefix Unused Variables With Underscore

We're always on the lookout for clever ways to make our code more readable and maintainable.
Today, let's explore a quick and fun little trick that involves prefixing unused variables in function arguments with an underscore (_). This simple technique can help us signal to others (and ourselves) that these variables are irrelevant to the current task at hand.

We can also only use an underscore without any variable. Still, the downside is that it can be confusing as to what this variable that we're ignoring is, and not as descriptive. (Eslint too will understand this syntax)

Imagine you're working on a web application that fetches data from an API. The API response includes a callback function with several arguments, but you're only interested in the first and last argument. Here's how the underscore prefix can help:

api.fetchData((data, _statusCode, headers) => {
  // Process 'data' and ignore '_statusCode'
  console.log(data, headers);
Enter fullscreen mode Exit fullscreen mode

In this example, you're using the api.fetchData function, which provides a callback with three arguments. By prefixing _statusCode with an underscore, you make it clear that you're intentionally ignoring this variable in your callback function. This practice enhances code readability and helps others understand your coding intentions.

Final Thoughts

The underscore prefix is a valuable convention for callbacks that provide more arguments than necessary. It simplifies code readability and helps convey your coding intentions clearly. So, the next time you encounter surplus callback arguments, don't hesitate to prefix the unused ones with an underscore. Your fellow developers (and future self) will appreciate the clarity and maintainability it brings to your code! 🚀

Top comments (0)