What does the void keyword do in JavaScript? Define with help of an example.
What is the use of void keyword in JavaScript?
33220-Jul-2021
Updated on 29-Nov-2023
Home / DeveloperSection / Forums / What is the use of void keyword in JavaScript?
What does the void keyword do in JavaScript? Define with help of an example.
Aryan Kumar
29-Nov-2023In JavaScript, the void keyword is used to evaluate an expression and then return undefined. It's often used in situations where you want to ensure that a particular expression returns undefined, regardless of what the expression itself evaluates to.
Here's a simple example:
In this example, someFunction() is called, but the void keyword ensures that the result assigned to result is always undefined, regardless of what someFunction() returns.
It's important to note that using void in this way is not very common in modern JavaScript code. It's often considered more readable and idiomatic to explicitly set a variable to undefined if that's what you want. The void keyword is more historically used in scenarios like creating self-invoking anonymous functions:
In this case, it ensures that the function is evaluated and returns undefined, and it's a way to encapsulate code without affecting the surrounding scope. However, using modern JavaScript practices, you might see other ways of achieving similar effects, like using arrow functions or IIFE (Immediately Invoked Function Expressions) without void.