Void means null. In JavaScript, the void is an operator, which is used when the function is not returning any value. This is a unary operator.
In Java, if we do not specify any return type then automatically that function or method becomes void. But, JavaScript is not typed checking language. So, the function always returns something. In some situations we do not need to return anything so, we must specify void operator in front of the function.
Concept will be more clear with help of example
Example 1
Use of void is to purposely generate the undefined value as follows:
<!DOCTYPE html> <html> <head> <title>Void-Keyword</title> </head> <body> <font color="blue"> <h1>Void operator with Numbers</h1> </font> <script> function getvalue(x,y,z) { x=void(y,z); document.write("x value : "+x+"<br> y value : "+y+"<br> z value: "+z); } getvalue(10,20,30); </script> </body> </html>
Output:
Example 2:
Use of void operator with function(without parameter)
<!DOCTYPE html> <html> <head> <title>Void with function</title> </head> <body> <font color="orange"> <h1>Void operator with function</h1> </font> <script> void function getvalue() { document.write("Numbers from 1 to 5<br>"); for(let i=1;i<=5;i++) { document.write(i+"<br>") } }(); </script> </body> </html
Output:
Example 3:
Use of void operator with function(with parameter)
<!DOCTYPE html> <html> <head> <title>Void</title> </head> <body> <font color="pink"> <h1>Void operator with function with parameter</h1> </font> <script> void function addnum(a,b) { var c=a+b; document.write("First number and "+a +" Second Number ="+b+" <br>Addition is ="+c); }(10,20); </script> </body>
Output:
Example 4:
JavaScript:void(0)
<html> <head> <script type = "text/javascript"> <!-- //--> </script> </head> <body> <p> The following won't react at all</p> <a href = "javascript:void(0)">Click me!</a> </body> </html>Output: