Why are use the void keyword in JS?

0 votes
25 views
Ravi Vishwakarma asked 8 days ago in Web Application by Ravi Vishwakarma

Why are use the void keyword in JS?    

1 Answer

0 votes
Ethan Karla answered 6 days ago by Ethan Karla
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
Example:
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
 <head>
         <meta charset='utf-8' />
  <title>ES6 void keyword Example</title>
 </head>
 <body>
  <br><br>
  <a href='javascript:void(func());'>
  Click me to activate alert
  </a>
  <br><br>
  <a href='javascript:void(document.body.style.backgroundColor='yellow');'>
  Click me to change the background
  </a>
   <script>
       var func = function () {
           alert('Hello this is void keyword demo !!!!!');
       };
  </script>
 </body>
</html>