Cover Image for JavaScript void
112 views

JavaScript void

The JavaScript void is an operator that takes an expression as an argument and evaluates it but returns the value undefined. The void operator is typically used to discard the return value of an expression and prevent the browser from navigating to a new page when a link or button is clicked.

The syntax of the void operator is as follows:

JavaScript
void expression

Here’s an example to demonstrate the usage of the void operator:

HTML<span role="button" tabindex="0" data-code="<a href="https://www.example.com" onclick="void(0)">Click me
<a href="https://www.example.com" onclick="void(0)">Click me</a>

In the above example, when the link is clicked, the onclick attribute calls the void operator with the argument 0. Since the void operator always evaluates the expression and returns undefined, clicking the link won’t navigate to the URL specified in the href attribute.

It’s important to note that the void operator is not commonly used in modern JavaScript development. Its primary use was to prevent navigation in older versions of JavaScript when using javascript: URLs. Nowadays, it’s more common to use event handlers and return false to prevent default behavior or use event.preventDefault() within an event handler function.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS