What is void(0) in JavaScript
In this article, you are going to learn about how to use void(0) in JavaScript.
In a normal sense, the word void refers to completely empty or blank. When it is used in programming languages, like JavaScript the word void(0) refers as it returns nothing.
This operator is mostly used with the hyperlink. We use hyperlinks in our project to add a link or to navigate into a new page or reload a page.
But if you want to use a hyperlink but not to do those stuffs that are mentioned above then you have to use javascript:void(0). This will tell the browser to do nothing.
You may use this operator in two ways like using void(0) or void 0. Both will work the same. Let’s see an example where I will demonstrate to you by using javascript:void(0) into one link and another one I will not use this operator and see what happens.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>JavaScript:Void(0) Example</title>
</head>
<body>
<div class="section">
<h1> JavaScript Void(0) Example </h1>
<a href = "javascript:void(0);">
Click me to get nothing
</a>
<br/><br/>
<a href = "javascript:alert('Good Morning!');">
Click me to get an alert message
</a>
</div>
</body>
</html>
Here, we add two links and first one we have used void(0) and another one we have written an alert message and we are expecting that when the first link will be clicked it will do nothing, and when the second link will be clicked it will show an alert message like Good Morning! Let’s see the output below:
Here, you can see that the moment we have clicked on the first link nothing happened because we have used javascript:void(0). Let’s check the second link if there any changes occurred or not
This time we have got an alert message with Good Morning! Here, you can see the differences and usage of the void(0) operator. If you need a link that will not perform any action then you can simply use this javascript:void(0) operator.