Open In App

What is the use of the Void Operator in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The void operator in JavaScript is like a special command that tells the computer to do something but not worry about what comes back. It’s often used when you want to make a clickable link on a website that doesn’t take you to a new page. Instead of saying “go nowhere,” you use ‘void(0)’ in the link, and it makes sure nothing happens, keeping things simple.

Example: Imagine you have a website with a button that you want to do something special when clicked, but you don’t want it to take you to a different page.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Void Operator Example</title>
</head>
 
<body>
 
    <button onclick="doSomething()">Click me</button>
 
    <script>
        function doSomething() {
            alert("Hello! I did something cool.");
        }
    </script>
 
</body>
 
</html>


when you click the button, the ‘doSomething()’ function is called, and it shows an alert saying “Hello! I did something cool.” The ‘void’ operator isn’t explicitly used here, but if you want to ensure that clicking the button doesn’t take you anywhere, you might modify the button like this:

<button onclick="void(0); doSomething()">Click me</button>

Adding ‘void(0);’ before the function call ensures that clicking the button won’t cause the page to change.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads