ES6 | Void Keyword

The void keyword in JavaScript ES6 is used to evaluate an expression and it does not return any value. It is a unary operator and takes a single operand. We commonly use it in hyperlinks. Sometimes, we may need to call some JavaScript from a link. When we click on a link, the browser loads a new page or refreshes the same page. But we don’t want that to happen if some JavaScript is attached to that link and the void operator is useful when we have to call another function, that might result in a page refresh.

Syntax:

void (expression)
void expression

Below examples illustrate the void keyword in ES6 JavaScript:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>ES6 void keyword Example</title>
        <style>
            body{
               text-align: center; 
            }
            h1 { color: green;
            }
        </style>
    </head>
    <body>
      
        <h1>GeeksforGeeks</h1>
        <b>A Computer Sciecnce Portal for Geeks</b>
        <br><br>
        <a href="javascript:void(func());">
         Click me to activate alert
        </a>
        <br><br>
        <a href=
"javascript:void(document.body.style.backgroundColor='#F08080');">
         Click me to change the background
        </a>
            <script>
            var func = function() {
                alert("HI!!!");
            };
        </script>
    </body>
  
</html>

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>ES6 void keyword Example</title>
        <style>
            body{
               text-align: center; 
            }
            h1 { color: green;
            }
        </style>
    </head>
    <body>
      
        <h1>GeeksforGeeks</h1>
        <b>A Computer Sciecnce Portal for Geeks</b>
        <br><br>
        <a href
"javascript:void(javascript:alert('A Computer Sciecne Portal'))"
         Click here for no alert 
        </a
        <br><br>
        <a href
"javascript:alert('GeeksforGeeks');">
            Click here for an alert
        </a>
    </body>
</html>            

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.