ES6 void Keyword

The void keyword is used as the return type of functions that do not return any value. It evaluates the given expression and returns undefined. It is an important JavaScript keyword that might be used as a unary operator and appears before the single operand of any type.

It specifies an expression to evaluate without returning any value. The void operator is often used for obtaining the undefined primitive value.

Syntax
void expression
Example
snippet
var x,y,z;  
x = void ( y = 50, z = 70 );
console.log('x = ' + x + ' y = ' + y +' z = ' + z );
Output
x = undefined y = 50 z = 70

Immediately Invoked function expressions (IIFE) and void keyword

Using an IIFE, the void can be used for forcing the function keyword to be treated as an expression rather than a declaration.

Example
snippet
void function hello() { 
   var msg = function () 
   {console.log("Welcome back!!")}; 
   msg(); 
}();
Output
Welcome back!!

JavaScript URI and void keyword

When a browser follows the URI, it evaluates the URI code and replaces the page content with the returned value unless the value is undefined. The JavaScript: URI has widely used syntax in an HTML page.

The void operator can be used to return the undefined value.

Let us understand the illustration for the same.

In the following example, we are defining two links that have alert boxes. In one link, we are using the void keyword. When the corresponding link gets clicked, then it evaluates the JavaScript alert and passes it to the void() operator. The void() operator will return an undefined value. Hence the alert function will not display on the page.

When you click on the second link, then it will display an alert dialog box.

Example
snippet
html> 

<head>  
</head> 
<body> 
    <center> 
        <h1>Hello World :) :)</h1> 
        <h2>Welcome to rookienerd</h2> 
        <h2>Click the following links to see the changes</h2> 
        <a href = "javascript:void(javascript:alert('hello world!!'))"> 
            It will do nothing.
          </a> 
          <br/><br/>
          <a href = "javascript:alert('Welcome to rookienerd');">Click here for an alert</a>
    </center> 
</body> 
  
</html>

After the successful execution of the above code, you will get the following output:

ES6 void Keyword

When you click on the first link, you will get nothing. But, on clicking the second link, you will get the following screen:

ES6 void Keyword
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +