Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Check if a Variable is of Function Type using JavaScript
Next article icon

What is void and when to use void type in JavaScript ?

Last Updated : 31 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will know what is void operator in Javascript, along with discussing the particular condition where void operator can be used & understanding their implementation through the examples.

The void keyword in JavaScript, is used to evaluate an expression which does not return any value. The void operator is an unary operator that accepts the single operand, which may be of any type. The importance of the void keyword come into role when we just need to evaluate an expression instead of returning its value. It means, by using it, we can prevent the browser from displaying the result of the execution of the expression.

Syntax:

void expression  void(expression)

The void operator has an operator precedence ie., the priority will be given to operators while parsing a statement that has more than one operator performing operations in it. Here, we have used the parenthesis, to express the purpose of the expression, according to its precedence.

For instance, consider the below example:

void (10 == '10') // undefined  void 10 == '10' // false

For the 1st case, when the number is compared with string, inside the parenthesis with the void keyword, it returns undefined whereas in the 2nd case, when the expression is evaluates directly with the void keyword, it returns false.

Example: This example describes the returning undefined value.

HTML
<script>        function foo() {            return void 0;        }        console.log(foo()); </script> 

Output:

undefined

void 0 can be used as a placeholder URL that represents an onclick event is tied to the link to perform the actual action. The void 0 is also commonly used in code downsizing, as it is a way of writing undefined. 

There are 3 instances where the void operator can be used:

Active Javascript URLs: The javascript: is referred to as the pseudo URL, when we provide it as a value of "href" in an anchor tag, the browser evaluates the expression that follows the ":" symbol. On the other hand, the expression that follows the ":" is usually used as a referenced path.

The void operator is most commonly used in managing the javascript: URL (s) because it allows the browser to show the end result of the evaluation of the expression rather than the returned value of the evaluated expression on the client side. 

Example: In this example, the link changes the color of the background to green without returning any value to the browser.

HTML
<!DOCTYPE html> <html>  <head>     <title>Using Void in URLs</title> </head>  <body>     <a href= "javascript:void(document.body.style.backgroundColor='#32CD32');">         Click here to change the background color.     </a>  </body>  </html> 

Output:

Inactive Javascript URLs: In some cases, it is not required by a link to navigate anywhere or do anything. To achieve it, we combine the pseudo URL (javascript:) with void(0) as a value of an href, it tells the browser to return/do nothing when that link is clicked. 

Example: This example explains the generating the inactive Javascript URL.

HTML
<html>  <head>       <title>Creating Inactive URL</title> </head>    <body>     <pre>         Syntax to make Inactive Javascript URLs:         <a href="javascript:void(0)">Click here to do nothing.</a>     </pre>  </body>  </html> 

Output: The link will be recognized by the browser but the link doesn't react at all. When 0 is passed to void as an argument, it does nothing or returns nothing. Here "Click here and do nothing" link doesn't do anything at all, as depicted in the output.

Suppression of Arrow Functions: Arrow functions provide a braceless syntax to return the value of an expression. To ensure that the return value of the function expression (when it is of no use) doesn't affect the code in any way, it can be passed into a void operator.

Example: This example explains the returning the value of an expression.

HTML
<html>  <head>     <title>Returning the value of an expression</title> </head>  <body>     <h3>Here we see how we can return undefined value on purpose:</h3>          <script>         function someOtherFunction(num) {             return num + 1         }         const toReturnUndefined = () => void someOtherFunction(1);         console.log(toReturnUndefined());     </script> </body>  </html> 

Output:

Returning Undefined Value on Purpose: We can convert any variable's value to an undefined type.

HTML
<html>  <head>     <title>Returning Undefined Value on Purpose</title> </head>  <body>     <h3>Click the following to Return the Undefined Value:</h3>     <input type="button"             value="Click Me"             onclick="genUValue();" />          <script>         function genUValue() {             var g, f, h;             g = void(f = 13, h = 19);             document.write('g = ' + g);         }     </script> </body>  </html> 

Output:

Immediately Invoked Function Expression: An Immediately Invoked Function Expression(IIFE) is a type of Javascript function which gets executed as soon as it gets defined. They are very useful because they don't affect the global object and the remote variable declarations very easily. We can use the void operator to create IIFEs. It will force the function to be treated as an expression rather than a declaration.

Example:

HTML
<html>  <head>     <title>Creating a IIFE Using the Void operator</title> </head>  <body>     <h3>Here we are creating a IIFE Using the Void operator:</h3>        <script>         void function iife() {             console.log("IIFE is made with void operator");         }();         iife();   </script> </body>  </html> 

Output:


Next Article
Check if a Variable is of Function Type using JavaScript

P

priyanshuchatterjee01
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • What is any type, and when to use it in TypeScript ?
    Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don't know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation.  In this article, we will see what is any
    3 min read
  • What is an unknown type and when to use it in TypeScript ?
    In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type.  similar to any, we can assign any va
    3 min read
  • What is the use of TypedArray Object in JavaScript ?
    Introduction: Arrays in Java and C++ are data structures, that are of fixed-size contiguous and store homogeneous data. These arrays utilize contiguousness and caching to improve performance thus reducing the random access time. However, JavaScript arrays are different beasts. Unlike typical arrays,
    4 min read
  • What is Variable Scope in JavaScript ?
    Variable scope is the context of the program in which it can be accessed. In programming, a variable is a named storage location that holds data or a value. Think of it as a container that you can use to store and manipulate information in your code. Variables allow you to work with data in a flexib
    4 min read
  • Check if a Variable is of Function Type using JavaScript
    A function in JavaScript is a set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called. [GFGTABS] javascript let gfg = function(){/* A set of statements */};
    3 min read
  • What is Strict Mode and how to enable it in JavaScript ?
    The strict mode of JavaScript, introduced in ECMAScript 5, is a mechanism to opt into a restricted version of JavaScript." Strict mode modifies the regular JavaScript semantics in the following ways: Some JavaScript silent errors are eliminated by converting them to throw errors. How to enable stric
    3 min read
  • How to Use JavaScript: void(0) and onClick?
    Using javascript:void(0) in combination with the onClick attribute is a technique used in HTML to create links or clickable elements that perform actions without navigating away from the page. This is common when you want to attach a JavaScript function or event handler to a clickable element but pr
    2 min read
  • What is spread, default and rest parameters in JavaScript ?
    The default, spread, and rest parameters were added in ES6. Default Parameter: It is used to give the default values to the arguments, if no parameter is provided in the function call. Syntax: function fnName(param1 = defaultValue1, ..., paramN = defaultValueN) { ... } Example 1: In the below exampl
    2 min read
  • What is the practical use for a closure in JavaScript?
    In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned. The below examples show the practical use of closures: Example: In this example, a variable mult is defined that is local to the function
    3 min read
  • JavaScript TypeError - "X" is not a function
    This JavaScript exception is not a function that occurs if someone trying to call a value from a function, but in reality, the value is not a function. Message: TypeError: Object doesn't support property or method {x} (Edge) TypeError: "x" is not a function Error Type: TypeError Cause of Error: Ther
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences