The word void means “completely empty space” according to the dictionary. This term, when used in programming, refers to a return of “nothing” - an “empty value” so to speak.
When a function is void, it means that the function returns nothing. This is similar to functions in JavaScript which return undefined
explicitly, like so:
function und() {
return undefined
}
und()
or implicitly, like so:
function und() {
}
und()
Regardless of the expressions and statements in the functions above (adds 2 numbers together, finds the average of 5 numbers, whatever), there is no result returned.
Now we know what the void
keyword is all about. What about javascript:void(0)
?
javascript:void(0)
?If we split this up, we have javascript:
and void(0)
. Let’s look at each part in more detail.
javascript:
This is referred to as a Pseudo URL. When a browser receives this value as the value of href
on an anchor tag, it interprets the JS code that follows the colon (:) rather than treating the value as a referenced path.
For example:
<a href="javascript:console.log('javascript');alert('javascript')">Link</a>
When “Link” is clicked, here is the result:
As seen above, the browser does not treat href
as a referenced path. Instead, it treats it as some JavaScript code starting after “javascript:” and separated by semi-colons.
void(0)
The void operator evaluates given expressions and returns undefined
.
For example:
const result = void(1 + 1);
console.log(result);
// undefined
1 + 1
is evaluated but undefined
is returned. To confirm that, here’s another example:
<body>
<h1>Heading</h1>
<script>
void(document.body.style.backgroundColor = 'red',
document.body.style.color = 'white'
)
</script>
</body>
#javascript #programming #web-development #developer