We often use the code javascript:void(0)
in JavaScript, but what does it represent?
The key part of javascript:void(0)
is the void keyword, which is an important keyword in JavaScript. This operator specifies the evaluation of an expression without returning a value.
The syntax format is as follows:
void func()
javascript:void func()
or
void(func())
javascript:void(func())
The following code creates a hyperlink that does nothing when clicked:
Example
<a href="javascript:void(0)">Clicking here does nothing</a>
When the user clicks the link, void(0) evaluates to 0, but has no effect on JavaScript.
In the following example, an alert message is displayed after the user clicks the link:
Example
<p>Click the link below to see the result:</p>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
In the following example, parameter a will return undefined:
Example
function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
Difference between href="#" and href="javascript:void(0)"
# contains location information, with the default anchor being #top, which is the top of the webpage.
On the other hand, javascript:void(0)
merely represents a dead link.
In cases where the page is very long, # is used to locate a specific position on the page, in the format: # + id.
If you want to define a dead link, use javascript:void(0)
.
Example
<a href="javascript:void(0);">Clicking me has no effect!</a>
<a href="#pos">Click me to navigate to a specific position!</a>
<br>
...
<br>
<p id="pos">End positioning point</p>