JavaScript – Void Keyword
In the world of JavaScript, you’ll often encounter unique keywords and operators, and ‘void’ is one such keyword that can raise questions for many developers. So, what exactly does the ‘void’ keyword do?
What is the ‘void’ Keyword?
In JavaScript, ‘void’ is a unary operator used to evaluate an expression and return ‘undefined’ as its result. It essentially discards the return value of an expression, making it particularly useful in specific scenarios.
Common Use Cases
- Preventing Default Actions: One practical use of the ‘void’ keyword is in HTML event handlers, such as
<a>tags with ‘javascript:void(0)’ in the ‘href’ attribute. This prevents the default action of navigating to a new page when the link is clicked.
<a href="javascript:void(0);" onclick="myFunction();">Click Me</a>Code language: HTML, XML (xml)
- Avoiding ‘undefined’ Output: When you want a function to execute without returning any value, you can use ‘void’ to ensure that ‘undefined’ is returned explicitly.
function logMessage(message) {
// Log the message and return undefined
console.log(message);
return void 0;
}Code language: JavaScript (javascript)
Practical Example
Consider a scenario where you want to create a button that triggers an action but shouldn’t change the current page. You can use the ‘void’ keyword in the ‘href’ attribute of an <a> tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using the 'void' Keyword</title>
</head>
<body>
<a href="javascript:void(0);" onclick="myFunction();">Click Me</a>
<script>
function myFunction() {
alert("Button Clicked!");
}
</script>
</body>
</html>Code language: JavaScript (javascript)
Output :

In this example, clicking the “Click Me” link triggers the ‘myFunction()’ JavaScript function without changing the page’s URL.
Conclusion
The ‘void’ keyword might initially seem obscure, but it serves a valuable purpose in JavaScript. It’s a tool for controlling the behavior of expressions, especially in scenarios where you want to prevent default actions or ensure that a function doesn’t return any value. Understanding when and how to use ‘void’ can make your JavaScript code more precise and efficient.
