The void operator evaluates the given expression and then returns undefined. If we pass as the unary expression operand to the void operator, JavaScript coerces to false
and returns it undefined (which means “do nothing”).
This method of “doing nothing” becomes useful when we want to insert hyperlinks that perform useful functions on the page. Such hyperlinks allow a user to click on one and then perform a useful function, like updating a value on the webpage without loading a new page.
void(0)
We can use Javascript void(0)
when we do not want the browser to load a new page or refresh the same page when a link is clicked.
Instead, we want the browser to perform the Javascript attached to that link.
The link above is displayed using the code shown below:
<a href="" onclick="alert('The page will reload!!!')">Click Here to display alert!</a>
Since it does not use void(0)
, clicking the link performs the intended function of displaying an alert, but it also reloads the page.
To prevent the page from performing the function and then reloading every time that this hyperlink is clicked, we need to modify our code slightly. In other words, we need to add javascript:void(0);
to the href
field in our hyperlink.
<a href="javascript:void(0);" onclick="alert('The page will not reload.')">Click Here to display alert!</a>
Once the hyperlink is clicked, javascript:void(0)
tells the browser to “do nothing,” hence preventing the browser from reloading the page while still performing the intended function.