Why does the JavaScript void statement evaluate an expression?


The JavaScript void returns an expression to remove the side effect and return the undefined primitive value. This side effect may occur while inserting expression in a web page.

Let’s see an example of the void. The void(0) can be used with hyperlinks to obtain the undefined primitive value,

Example

Live Demo

<!DOCTYPE html>
   <html>
      <head>
         <title>Understanding JavaScript void(0)</title>
      </head>
   <body>
      <a href="javascript:void(0);" ondblclick="alert('Click it twice!')">Click me not once, but twice.</a>
   </body>
</html>

We used JavaScript:void(0) above to prevent the page from reloading when the button is clicked the first time.

The code will only work when the button will be clicked twice. If it is clicked once, then nothing happens. But the alert box comes over when the button is clicked twice since we used the ondblclick event handler.

Updated on: 10-Jan-2020

48 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements