- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use void keyword in JavaScript?
In this tutorial, let us discuss how to use the void keyword in JavaScript.
We use the void keyword as the return type of function that does not return any value. It evaluates an expression and returns undefined. We can use this with a single operand because this is a unary operator.
We should not wrap the expression in parentheses because void is not a function. void 0 is the same as void(0).
Users can follow the syntax blocks to deal with each use case.
Syntax
void expression
The expression can be a variable or a function.
Use void Keyword with Immediately Invoked Function Expressions
Immediately Invoked Function Expression (IIFE) lets the void keyword work as an expression rather than a declaration.
For example, we need to run the below code snippet.
function execute(){}()
Syntax
void (function execute() {})(); (function execute() {})();
We can write the first code snippet in two ways, as given above, with the void.
Example
In this program, we add a void to an IIFE function. Therefore, the function returns undefined.
<html> <body> <h2>Program:<i>IIFE with void</i></h2> <div id="IIFEVoidBtnWrap"> <button onclick="IIFEVoidOutput()">Click Me</button> </div> <p id="IIFEVoidOut"></p> <script> function IIFEVoidOutput() { var IIFEVoidBtnWrap = document.getElementById("IIFEVoidBtnWrap"); var IIFEVoidOut = document.getElementById("IIFEVoidOut"); IIFEVoidBtnWrap.style.display = "none"; const IIFEFunction = void function IIFEFunction1() { return 'IIFEFunction1'; }(); IIFEVoidOut.innerHTML = "<b>Output</b> : " + IIFEFunction; } </script> </body> </html>
Use void keyword with URI
The browser evaluates the URI code and returns the value to the page when we use the void keyword with the URI.
Hyperlinks open by reloading the page when the user clicks on the link. When you need to run some other code in such cases, you can use javascript: void(0).
Syntax
javascript:void 0
It returns nothing.
Example
In this program, the first link reloads the page when the user clicks on it. The second link remains the same because void 0 restricts page reload.
<html> <body> <h2>Program:<i>javascript: void(0)</i></h2> <a href=""ondblclick="alert('Twice')">Page reload</a><br><br> <a href="javascript: void(0)" ondblclick="alert('Twice')">No page reload</a> </body> </html>
Use void keyword with a conditional statement
Syntax
if(value===void(0)) {}
Void can compare an undefined variable or data to an undefined one.
Example
In this program, the first function call has no arguments. Therefore, it displays undefined with the condition check with the void. The second function call has a value, and hence user can see that value in the output.
<html> <body> <h2>Program: <i>conditions with void</i></h2> <div id="checkVoidBtnWrap"> <button onclick="checkVoidOutput()">Click Me</button> </div> <p id="checkVoidOut"></p> <script> function checkVoidOutput() { var checkVoidBtnWrap = document.getElementById("checkVoidBtnWrap"); var checkVoidOut = document.getElementById("checkVoidOut"); //checkVoidBtnWrap.style.display = "none"; var checkVoidCbk = function(value) { if(value===void(0)) return "Nothing"; else return value; }; checkVoidOut.innerHTML = "<b>Output</b><br><br> " + checkVoidCbk() + "<br><br>"+ checkVoidCbk("Hello"); } </script> </body> </html>
Use void keyword with non-leaking arrow functions
Arrow functions return an expression. In a few cases, it returns unexpected results of a function call that returns nothing. In such cases, the void can help because it does not return anything.
Syntax
button.onclick = () => void doAction();
It returns nothing, even if an unexpected outcome comes in.
Example
In this program, we set an arrow function with the void key to avoid any wrong actions that may happen.
<html> <body> <h2>Program: <i>arrow function with void</i></h2> <div id="arrowVoidBtnWrap"> <button id="arrowVoidBtn">Click Me</button> </div> <p id="arrowVoidOut"></p> <script> var arrowVoidBtnWrap = document.getElementById("arrowVoidBtnWrap"); var arrowVoidBtn = document.getElementById("arrowVoidBtn"); var arrowVoidOut = document.getElementById("arrowVoidOut"); function arrowVoidOutput() { arrowVoidOut.innerHTML = "Returns Nothing"; } arrowVoidBtn.onclick = () => void arrowVoidOutput(); </script> </body> </html>
Use void keyword with asynchronous calls
Syntax
(async () => { try { const resp = await fetch('API'); const res = await response.result(); } catch(e) {} })();
Void can help in the case of asynchronous API calls.
Example
This program uses invalid syntax with an asynchronous function and displays the result.
<html> <body> <h2>Program: <i>asynchronus calls with void</i></h2> <div id="asyncVoidBtnWrap"> <button id="asyncVoidBtn" onclick="asyncVoidDoAction()">Click Me</button> </div> <p id="asyncVoidOut"></p> <script> var asyncVoidBtnWrap = document.getElementById("asyncVoidBtnWrap"); var asyncVoidOut = document.getElementById("asyncVoidOut"); function asyncVoidDoAction() { (async () => { try { const resp = await fetch('API'); const res = await response.result(); asyncVoidOut.innerHTML = res; } catch(e) { asyncVoidOut.innerHTML = e; } })(); } </script> </body> </html>
Use void keyword to generate undefined values
Syntax
void(variable=value)
It returns undefined.
Example
In this program, we use the void keyword to return the value undefined and display both actual and undefined values to the user.
<html> <body> <h2>Program: <i>undefined value with void</i></h2> <div id="undefValVoidBtnWrap"> <button id="undefValVoidBtn">Click Me</button> </div> <p id="undefValVoidOut"></p> <script> var undefValVoidBtnWrap = document.getElementById("undefValVoidBtnWrap"); var undefValVoidBtn = document.getElementById("undefValVoidBtn"); var undefValVoidOut = document.getElementById("undefValVoidOut"); undefValVoidBtn.onclick = function() { var num1, num2, num3, num4; num1=10, num2=void (num3=30, num4=40); undefValVoidOut.innerHTML = ('num1 = ' + num1 + '<br><br>num2 = ' + num2 + '<br><br>num3 = ' + num3 + '<br><br>num4 = ' + num4); }; </script> </body> </html>
Use void keyword to generate one-time functions
Syntax
void function doAction() {}(); try{ doAction();} catch(e) {}
Void makes the function undefined for the second time.
Example
In this program, we define a function with the void keyword. The function call throws an error when we call it for the second time. The try-catch block handles the error case.
<html> <body> <h2>Program: <i> one-time function with void</i></h2> <div id="oneTimeFnVoidBtnWrap"> <button id="oneTimeFnVoidBtn">Click Me</button> </div> <p id="oneTimeFnVoidOut"></p> <script> var oneTimeFnVoidBtnWrap = document.getElementById("oneTimeFnVoidBtnWrap"); var oneTimeFnVoidBtn = document.getElementById("oneTimeFnVoidBtn"); var oneTimeFnVoidOut = document.getElementById("oneTimeFnVoidOut"); var oneTimeFnStr = ""; oneTimeFnVoidBtn.onclick = function() { void function oneTimeFnVoid() { oneTimeFnStr += "One-time function<br><br>"; }(); try { oneTimeFnVoid(); } catch(e) { oneTimeFnStr += e; } oneTimeFnVoidOut.innerHTML = oneTimeFnStr; }; </script> </body> </html>
Usecases
void console.log("test"); //test void("test"); //undefined (void(2 =="2")); //undefined (void(2)=="2"); //false (void(2)==undefined);// true
Operator Precedence
If there is more than one operand, we should put parenthesis.
void 10+20;//void(10)+20
Drawbacks
void is a keyword. We can not use it as a variable name. Therefore, we cannot change its definition.
eval('const void=100'); //Uncaught SyntaxError: Unexpected token 'void'
This tutorial taught us the void keyword uses. It just helps to minimize code but affects code readability.