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.


void expression


var x,y,z;  
x = void ( y = 50, z = 70 );
console.log('x = ' + x + ' y = ' + y +' z = ' + z );


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.


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


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.


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


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 #