Home > Article > Web Front-end > Understanding the Use of Underscore (`_`) in JavaScript
When coding in JavaScript, you may come across the underscore character (_) used as a variable name, particularly in function parameters. While it may seem unusual at first glance, this practice is common among developers for various reasons. In this blog post, we'll explore what the underscore represents, why it's used, and how it appears in real-world examples, like the coalesceES6 function.
In JavaScript, the underscore (_) is often used as a placeholder for a variable, especially when the variable’s identity is not important to the logic of the code. This convention helps indicate that the variable is temporary and serves a specific purpose, usually for iteration or as a callback parameter.
To illustrate the use of the underscore, let’s look at a simple function called coalesceES6. This function takes multiple arguments and returns the first one that is neither null nor undefined.
Here’s how the function looks:
const coalesceES6 = (...args) => args.find(_ => ![null, undefined].includes(_));
Breaking It Down:
Arrow Function:
Finding Non-Nullish Values:
Using _:
Indicates a Temporary Variable:
Conciseness:
Familiarity in the Community:
While using _ is common, it's not the only option. Developers can also choose more descriptive variable names to enhance readability:
const coalesceDescriptive = (...args) => args.find(arg => ![null, undefined].includes(arg));
In this version, arg is used instead of _. While this improves clarity, the function’s logic remains the same. The choice between using _ or a descriptive name often comes down to personal or team preference.
The underscore (_) is a simple yet powerful convention in JavaScript. It serves as a placeholder variable, making code cleaner and signaling to others that the variable's identity is not crucial to the overall logic. In functions like coalesceES6, using _ allows developers to focus on the functionality rather than the specifics of variable naming.
Next time you see the underscore in JavaScript, you'll know that it's not just a random choice, but a thoughtful decision that contributes to clear and concise coding practices.
The above is the detailed content of Understanding the Use of Underscore (`_`) in JavaScript. For more information, please follow other related articles on the PHP Chinese website!