From what I understand, the keyword void
in Javascript is some kind of function that takes one argument and always returns the undefined
value. For some reason you need to pass it an argument; it won't work without one.
Is there any reason why it requires this argument?
What is the point? Why won't it work without an argument. The only use I have seen for it is to produce an undefined
result. Are there any other uses for it?
If not then it would seem that the requirement for an expression to be passed would be pointless.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
Using javascript: , you can run code that does not change the current page. This, used with void(0) means, do nothing - don't reload, don't navigate, do not run any code. The "Link" word is treated as a link by the browser. For example, it's focusable, but it doesn't navigate to a new page.
It is also used as a generic pointer (e.g., void* ), although this usage is needed less often in C++ than in C. C++ does not require that void be used to indicate that there are no function parameters, but it is often used in this way for compatibility with C.
To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses. The order and types of the list of arguments should correspond exactly to those of the formal parameters declared in the function prototype.
As per this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void void is an operator, which simply returns undefined
, after evaluating the expression you pass to it. An operator needs an operand to operate on. That is why pass a parameter.
console.log(void true);
console.log(void 0);
console.log(void "Welcome");
console.log(void(true));
console.log(void(0));
console.log(void("Welcome"));
All these statements would print undefined
var a = 1, b = 2;
void(a = a + b)
console.log(a);
And this would print 3
. So, it is evident that, it evaluates the expressions we pass to it.
Edit: As I learn from this answer https://stackoverflow.com/a/7452352/1903116
undefined
is just a global property which can be written to. For example,
console.log(undefined);
var undefined = 1;
console.log(undefined);
It prints
undefined
1
So, if you want to absolutely make sure that the undefined
is used, you can use void
operator. As it is an operator, it cannot be overridden in javascript.
void
also evaluates the expression you pass to it. It doesn't just return undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With